Python - Extracting a substring using a for loop instead of Split method or any other means [duplicate]

妖精的绣舞 提交于 2019-12-12 13:29:33

问题


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)

回答1:


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)


来源:https://stackoverflow.com/questions/18599398/python-extracting-a-substring-using-a-for-loop-instead-of-split-method-or-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!