![](/img/trans.png)
[英]How would you use a `for` or `while` loop to find the nth word in a sentence
[英]How to break a while loop when you reach a certain letter in a sentence
我正在编写这段代码,我打算在代码到达字母“d”时中断 while 循环,但它不起作用。 我做错了什么? 此外,在代码的末尾,我的意思是 o 显示了其余的短语,但这也不起作用。
word_input = 'How hard is this?'
stop_at_letter = 'd'
i = 0
print('While loop a')
while i < len(word_input):
print(word_input[i])
i = i + 1
if i == stop_at_letter:
break
else:
print('Remaining letters are:' + str(word_input))
代替:
if i == stop_at_letter:
做:
if word_input[i] == stop_at_letter
注意:提问时将代码直接放在其正文中,不要随附图片。
您目前在代码中所做的是将变量“i”(我假设您将其用作计数器)与要停止的字符进行比较。
所以你基本上是将 0 与 'd'、1 与 'd' 进行比较...等
而不是这样做,你想使用索引来获取字符串中的正确字符(所以word_input[i]
)并将其与 stop_at_letter 进行比较。
此外,为了获得单词的其余部分,您可以使用slicing ,它基本上应该类似于word_input[i:len(word_input)]
。
将您的代码复制粘贴到您的帖子中而不是发布图片总是一个好主意,因此我们可以更轻松地重现您的问题。
word_input = 'How hard is this?!'
stop_letter = 'd'
result = []
for i in word_input:
result.append(i)
finalResult = ''.join(result)
if i == stop_letter:
break
print(finalResult)
输出:
How hard
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.