[英]How to use the loop integers in the list as indices for slicing a string
我有一个整数列表: words = [0,4,10,15]
和一个字符串s ='heliCopterRotorMotor'
我的任务是将这些整数作为索引应用于字符串以对其进行切片。 例如: s[words[0:4]]
应该是heli
s[words[4:10]]
应该是Copter
等。我写的代码不起作用:
s = 'heliCopterRotorMotor'
words = [0,4,10,15]
spisok = []
for i in words:
print(s[words[i:i+1]])
有人可以帮忙吗?
您正在切片列表words
,而不是实际的字符串。
你会想做这样的事情:
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
你可以通过一些切片和技巧来获得它们:
s = 'heliCopterRotorMotor'
words = [0,4,10,15]
for start, end in zip(words, words[1:] + [None]):
print(s[start:end])
heli
Copter
Rotor
Motor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.