Home > Net >  How to use the loop integers in the list as indices for slicing a string
How to use the loop integers in the list as indices for slicing a string

Time:10-05

I have a list of integers: words = [0,4,10,15] and a string s ='heliCopterRotorMotor'

My task is to apply those integers as indices to the string to slice it. For example: s[words[0:4]] should be heli s[words[4:10]] should be Copter etc. The code I wrote is not working:

s = 'heliCopterRotorMotor'
words = [0,4,10,15]
spisok = []
for i in words:
   print(s[words[i:i 1]])

Can anyone help, please?

CodePudding user response:

You are slicing the list words, not the actual string.

You would want to do something like this instead:

s = 'heliCopterRotorMotor'
words = [0,4,10,15]
for i in range(len(words)-1):
    print(s[words[i]:words[i 1]])

Output:

heli
Copter
Rotor

CodePudding user response:

You can get them all with some slicing and trickery:

s = 'heliCopterRotorMotor'
words = [0,4,10,15]

for start, end in zip(words, words[1:]   [None]):
   print(s[start:end])

heli
Copter
Rotor
Motor
  • Related