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

时间:2013-09-03 18:46:17

标签: python string for-loop substring extract

我正在使用online Python course这会导致程序员使用for循环提取子字符串的问题。一年前有一个问similar question,但它没有真正得到答案。

所以问题是:

  

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

给出的第一个HINT是

  

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

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

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

** SPOILER ALERT - 编辑以显示任何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)

1 个答案:

答案 0 :(得分:1)

如果您想使用循环执行此操作,请使用enumerate

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

enumerate返回索引和迭代/迭代器中的项。

>>> 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)