首页 > 解决方案 > 当可以在字符串中找到两个特定字母时,中断 while 循环

问题描述

我有一个字符串变量(mystring)。在 while 循环中,用户可以输入字符串的内容,我想在它包含 letter'a'和 letter时打破循环'b'。我尝试了以下方法:

mystring = ''

while 'a' or 'b' not in mystring:
    mystring = input('write:')

如果我只使用其中一个字母(没有or声明),while 循环就可以完美运行。如果我检查 mystring 例如在输入后'abacjihgea'使用

'a' and 'b' in mystring

它返回True。那它不应该打破while循环吗?

不幸的是,我似乎无法解决这个问题。

标签: pythonwhile-loopconditional-statements

解决方案


您应该单独检查并使用 and 条件

while ('a' not in mystring) and ('b' not in mystring) :
     mystring=input()

一种更简洁的方法是对多个字符使用集合和交集

while not {'a','b'}.issubset(mystring):
    mystring=input()

推荐阅读