string - Python - Extracting a substring using a for loop instead of Split method or any other means -
this question exact duplicate of:
- splitting input 2 for-loop 2 answers
i'm taking online python course poses problem programmer extract substring using loop. there similar question asked year ago, didn't answered.
so problem reads:
write program takes single input line of form «number1»+«number2», both of these represent positive integers, , outputs sum of 2 numbers. example on input 5+12 output should 17.
the first hint given is
use loop find + in string, extract substrings before , after +.
this attempt, know wrong because there no position in loop equals '+'. how find position '+' in string "5+12"?
s = input() s_len = len(s) position in range (0,s_len): if position == '+': print(position[0,s_len])
**spoiler alert - edit show csc waterloo course takers answer
s = input() s_len = len(s) 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 want using loop:
s = input() position, character in enumerate(s): if character == '+': print(position) break # break out of loop once character found
enumerate
returns both index , item iterable/iterator.
>>> list(enumerate("foobar")) [(0, 'f'), (1, 'o'), (2, 'o'), (3, 'b'), (4, 'a'), (5, 'r')]
working version of solution:
s = input() s_len = len(s) position in range(0, s_len): if s[position] == '+': #use indexing fetch items string. print(position)
Comments
Post a Comment