简体   繁体   English

当你到达句子中的某个字母时如何打破while循环

[英]How to break a while loop when you reach a certain letter in a sentence

I have this code I am writing and I am meant to break the while loop when the code reaches the letter 'd', but it isn't working.我正在编写这段代码,我打算在代码到达字母“d”时中断 while 循环,但它不起作用。 What did I do wrong?我做错了什么? Also, at the end of the code I am meant o have the rest of the phrase showing and that is not working either.此外,在代码的末尾,我的意思是 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))

Instead of:代替:

if i == stop_at_letter:

Do:做:

if word_input[i] == stop_at_letter

Note: when asking questions put your code directly to its body don't post pictures with it.注意:提问时将代码直接放在其正文中,不要随附图片。

What you're doing at the moment in your code is comparing the variable 'i', which I assume you're using as a counter, to the character you want to stop at.您目前在代码中所做的是将变量“i”(我假设您将其用作计数器)与要停止的字符进行比较。

So you're basically comparing 0 to 'd', 1 to 'd'.. etc所以你基本上是将 0 与 'd'、1 与 'd' 进行比较...等

Instead of doing that you want to use the index to get the right character in the string ( so word_input[i] ) and compare that with stop_at_letter.而不是这样做,你想使用索引来获取字符串中的正确字符(所以word_input[i] )并将其与 stop_at_letter 进行比较。

Also, in order to get the remainder of the word, you can use slicing , which should basically look like word_input[i:len(word_input)] .此外,为了获得单词的其余部分,您可以使用slicing ,它基本上应该类似于word_input[i:len(word_input)]

It's always a good idea to copy paste your code into your post instead of posting an image, so we have an easier time reproducing your problem.将您的代码复制粘贴到您的帖子中而不是发布图片总是一个好主意,因此我们可以更轻松地重现您的问题。


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)

Output:输出:

How hard

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM