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)