Python:使用 .find() 而不是 .split()
Python: Using .find() instead of .split()
我正在尝试使用 .find() 而不是 .split() 来寻找一种在字符串中打印单个单词的方法。我下面的代码将打印前两行,然后是两个空格。我试过在第 7 行使用 space_index += quote.find(" ", space_index + 1)
,但这会导致程序永远打印空格。我错过了什么?
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)
非常接近。只是在更新 start
时将 +=
更改为 =
。请记住,space_index
是整个字符串中 space 的索引,而不是从之前的 space.
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(" ", start)
print(quote[start:])
我正在尝试使用 .find() 而不是 .split() 来寻找一种在字符串中打印单个单词的方法。我下面的代码将打印前两行,然后是两个空格。我试过在第 7 行使用 space_index += quote.find(" ", space_index + 1)
,但这会导致程序永远打印空格。我错过了什么?
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)
非常接近。只是在更新 start
时将 +=
更改为 =
。请记住,space_index
是整个字符串中 space 的索引,而不是从之前的 space.
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(" ", start)
print(quote[start:])