我想使用索引切片将 word = "They stumple who run fast"
中的每个单词打印在新的一行上。
我试过使用 while
循环,比如在每个空格后打印单词
word = "They stumble who run fast"
space = word.count(' ')
start = 0
while space != -1:
print(word[start:space])
结果应该是这样的:
They
stumble
who
run
fast
最佳答案
如果你绝对需要使用索引切片:
word = "They stumble who run fast"
indexes = [i for i, char in enumerate(word) if char == ' ']
for i1, i2 in zip([None] + indexes, indexes + [None]):
print(word[i1:i2].strip())
输出:
They
stumble
who
run
fast
但为什么不用.split()
?
word = "They stumble who run fast"
print(*word.split(), sep='\n')
输出:
They
stumble
who
run
fast
关于python - 使用索引切片打印字符串中的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54122708/