Skip to content Skip to sidebar Skip to footer

Python - Extracting A Substring Using A For Loop Instead Of Split Method Or Any Other Means

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

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

Post a Comment for "Python - Extracting A Substring Using A For Loop Instead Of Split Method Or Any Other Means"