Python—使用for循环而不是Split方法或任何其他方法提取子字符串

Python—使用for循环而不是Split方法或任何其他方法提取子字符串,python,string,for-loop,substring,extract,Python,String,For Loop,Substring,Extract,我使用了一个例子,它提出了一个问题,程序员使用for循环提取子字符串。一年前有一个问题,但没有得到回答 所以问题是: 编写一个程序,采用«number1»+«number2»形式的单个输入行,其中这两行都表示正整数,并输出两个数字的总和。例如,在输入5+12时,输出应为17 给出的第一个提示是 使用for循环查找字符串中的+,然后提取+前后的子字符串 这是我的尝试,我知道这是错误的,因为循环中没有它等于“+”的位置。如何找到“+”在字符串“5+12”中的位置 **剧透警报-编辑以向任何CSC滑铁

我使用了一个例子,它提出了一个问题,程序员使用for循环提取子字符串。一年前有一个问题,但没有得到回答

所以问题是:

编写一个程序,采用«number1»+«number2»形式的单个输入行,其中这两行都表示正整数,并输出两个数字的总和。例如,在输入5+12时,输出应为17

给出的第一个提示是

使用for循环查找字符串中的+,然后提取+前后的子字符串

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

**剧透警报-编辑以向任何CSC滑铁卢课程学员显示答案

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)

如果要使用循环执行此操作,请使用
枚举

S = input()
for position, character in enumerate(S):
   if character == '+':
      print(position)
      break  # break out of the loop once the character is found
enumerate
从iterable/iterator返回索引和项

>>> list(enumerate("foobar"))
[(0, 'f'), (1, 'o'), (2, 'o'), (3, 'b'), (4, 'a'), (5, 'r')]
解决方案的工作版本:

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)

谢谢阿什维尼!我没有想到把这个位置作为字符串的索引@StacyM很高兴这有帮助。Martijn,Ashwini最终为原来的重复问题提供了更好的答案。那么,这不值得重新发布吗?我同意!
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)