Reputation: 123
I am writing a program in python, it's very simple I just want to know how to make make the input from a user true if it only contains m, u or i in it but absolutely nothing else. my code runs but if the input is 'miud' it will return true because m i and u are in it. the code below is what I have so far, how can I change it to make it allow only the letters m u and i?
x=input("Enter your string")
if 'm' in x and 'i' in x and 'u' in x:
print("true")
else:
print("false")
Upvotes: 0
Views: 39
Reputation: 14664
Use all built-in.
string = input("Enter your string")
print(all(char in ['m', 'i', 'u'] for char in string))
Basically,
(char in ['m', 'i', 'u'] for char in string)
builds an iterable that yields booleans. For each char in the string (starting from the first), this iterator yields True
if the char is m, i or u, False
otherwise.
Then you feed all()
this iterator:
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable): for element in iterable: if not element: return False return True
all
iterates over the newly created iterator and returns False
as soon as it gets a False
, or True
if it gets only True
values.
The beauty of iterators is that no True
/ False
list is ever computed: the tests are done on the fly and all
stops as soon as a char is found that is not neither of m, i, or u. Not relevant here, but this can have a performance impact in some applications.
Upvotes: 3
Reputation: 131978
You can use a set for that,
if set(x).issubset({'m', 'u', 'i'}):
print("true")
else:
print("false")
This code makes use of sets and the issubset
method. Since a string is an iterable so it can be used as an argument to set()
. The set will contain unique items (in this case each unique character from the input string).
That value can be tested against the known valid characters (also in a set) with the issubset
method.
{'m', 'u', 'i'}
is one way of creating a set, but this would work too:
if set(x).issubset(set('mui')):
Upvotes: 3