0

I have a string variable (mystring). In a while loop the user can input the content of the string and I want to break the loop when it contains the letter 'a' and the letter 'b'. I tried the following:

mystring = ''

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

the while loop works perfect if I use just one of the letters (no or statement). If I check mystring e.g. after inputting 'abacjihgea' using

'a' and 'b' in mystring

it returns True. Shouldn't it break the while loop then?

Unfortunately I can't seem to fix this problem.

Wolf
  • 9,679
  • 7
  • 62
  • 108
maxed
  • 11
  • 3
  • 4
    Does this answer your question? [What is the best approach in python: multiple OR or IN in if statement?](https://stackoverflow.com/questions/17615020/what-is-the-best-approach-in-python-multiple-or-or-in-in-if-statement) and [How to test multiple variables against a single value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-single-value) – Guy Jun 09 '21 at 07:51
  • 2
    `while (a not in mystring) and (b not in mystring):`? – Thomas Weller Jun 09 '21 at 07:54
  • Thanks Thomas Weller! That did the trick! – maxed Jun 09 '21 at 07:57
  • @rdas I do not see that the dup target (question and answers) should help in this case, so I vote to reopen. – Wolf Jun 09 '21 at 08:56
  • @Guy I mean, for people who are familiar with `in` and boolean expressions, the dup relation is easy to see but it is not for beginners not aware what they actually do. Look for example at `0 < x < 10` in Python which looks like school math but isn't... – Wolf Jun 09 '21 at 09:10
  • @rdas BTW: is it possible to change the dup target to https://stackoverflow.com/q/15112125/2932052 which contains answers explaining the issue. – Wolf Jun 09 '21 at 09:14

2 Answers2

1

You should check separately and with an and condition

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

A cleaner method is using set and intersection for multiple chars

while not {'a','b'}.issubset(mystring):
    mystring=input()
rojjot
  • 21
  • 4
0

You can use Regular expression as well. If order of letters is certain e.g. a followed by b then a.*b otherwise (a.*b|b.*a).

import re
mystring = ''

while not re.search('(a.*b|b.*a)',mystring):
    mystring = input('write:')
  • not quite efficient and not good to generalize. What if you have a list of letters *variables* to search for: build a complex regex? – Wolf Jun 09 '21 at 08:49