gpt4 book ai didi

python - 使用索引切片打印字符串中的每个单词

转载 作者:行者123 更新时间:2023-11-28 22:13:13 25 4
gpt4 key购买 nike

我想使用索引切片将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com