Python - 使用for循环而不是Split方法或任何其他方法提取子字符串 [英] Python - Extracting a substring using a for loop instead of Split method or any other means

查看:470
本文介绍了Python - 使用for循环而不是Split方法或任何其他方法提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参加了一个在线Python课程,程序员是使用for循环提取一个子字符串。一年前问了一个类似的问题,所以问题是:
$ b


编写一个程序它采用形式为number1+number2的单一输入行,其中两个表示正整数,并输出两个数的和。例如在输入5 + 12的输出应该是17。

给出的第一个提示是


使用for循环在字符串中查找+,然后在+之前和之后提取子字符串。

这是我的尝试,我知道是错误的,因为在循环中没有等于+的位置。如何找到'+'在字符串5 + 12中的位置?



pre $ S $ input $
s_len = len(S)
(0,s_len):
如果position =='+':
print(position [0,s_len])

** SPOILER ALERT - 编辑显示任何CSC滑铁卢课程参加者的答案

pre $ s $ input $ b $ s_len = len(S)
(0,s_len):
如果S [position] =='+':
number1 = int(S [0:position])
number2 = int(S [position:s_len])
sum = number1 + number2
print(sum)


解决方案

c $ c> enumerate ,如果你想用循环来做:

  S =输入()
位置,枚举(S)中的字符:
如果字符=='+':
打印(位置)
break#一旦出现字符被发现

枚举返回iterable / iterator中的索引和项目。

 >>>列表(枚举(foobar))
[(0,'f'),(1,'o'),(2,'o'),(3,'b'), a'),(5,'r')]

解决方案的工作版本:

  S = input()
s_len = len(S)
在范围(0,s_len)中的位置:
如果S [position] =='+':#使用索引从字符串中获取项目。
print(position)


I'm taking an online Python course which poses a problem where the programmer is to extract a substring using a for loop. There was a similar question asked a year ago, but it didn't really get answered.

So the problem reads:

Write a program that takes a single input line of the form «number1»+«number2», where both of these represent positive integers, and outputs the sum of the two numbers. For example on input 5+12 the output should be 17.

The first HINT given is

Use a for loop to find the + in the string, then extract the substrings before and after the +.

This is my attempt, which I know is wrong because there is no position in the loop where it equals a '+'. How do I find the position where the '+' is in the string "5+12"?

S = input()
s_len = len(S)
for position in range (0,s_len):
   if position == '+':
      print(position[0,s_len])

**SPOILER ALERT - Edit to show any CSC Waterloo course takers the answer

S = input()
s_len = len(S)
for position in range (0,s_len):
   if S[position] == '+':
      number1 = int(S[0:position])
      number2 = int(S[position:s_len])
sum = number1 + number2
print(sum)

解决方案

Use enumerate, if you want to do this using a loop:

S = input()
for position, character in enumerate(S):
   if character == '+':
      print(position)
      break  # break out of the loop once the character is found

enumerate returns both index and the item from the iterable/iterator.

>>> list(enumerate("foobar"))
[(0, 'f'), (1, 'o'), (2, 'o'), (3, 'b'), (4, 'a'), (5, 'r')]

Working version of your solution:

S = input()
s_len = len(S)
for position in range(0, s_len):
   if S[position] == '+':        #use indexing to fetch items from the string.
      print(position)

这篇关于Python - 使用for循环而不是Split方法或任何其他方法提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆