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



我想使用索引切片在新行上打印word = "They stumble 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
我想

我知道这个问题是干什么用的(edx class..因为我遇到了同样的事情)。这个解决方案对我有用,使用了他们鼓励学生在课程中这一点上使用的部分:

quote = "they stumble who run fast"
start = 0
space_index = quote.find(" ")
while space_index != -1:
    print (quote[start:space_index])
    start = space_index+1
    space_index = quote.find(" ", space_index+1)
else:
    print (quote[start::1])

如果学生需要示例并且必须进行索引切片,则以另一种方式发布。

    check = 0 # Here we start slicing at zero
    
    split = 0
    
    for x in word:
        if x == ' ':  # Will check for spaces
            print(word[check:split])
            check = split + 1  # check will inherit splits value plus one when space found
        split = split + 1  # spit will increase each time no space is found
    print(word[check:split])  # needed to print final word

显而易见的解决方案是使用 str.split ,但这会违反您对切片的愿望:

for w in word.split():
    print(w)

更好的方法可能是跟踪当前空间的索引并继续寻找下一个索引。这可能与您的想法相似,但您的循环不会更新和变量:

start = 0
try:
    while True:
        end = word.index(' ', start)
        print(word[start:end])
        start = end + 1
except ValueError:
    print(word[start:])

一个快捷方式,可能也不是可接受的,但会产生所需的输出:

print(word.replace(' ', 'n'))

不知道为什么有人想这样做而不仅仅是使用str.split(),但这是另一种(相当丑陋的)方法,沿着你最初刺伤它的路线。

word = "They stumble who run fast"
while ' ' in word:
    i = word.index(' ')
    print(word[:i])
    word = word[i+1:]
print(word)
# OUTPUT
# They
# stumble
# who
# run
# fast

让我们尽量不要想太多。

如果您不需要索引切片,则只需执行以下操作:

word = "They stumble who run fast"
print (word.replace(" ", 'n'))

最新更新