Timothy Kardaras Timothy Kardaras - 1 year ago 74
Python Question

Input issue Python

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:

Answer Source

You can use a set for that,

if set(x).issubset({'m', 'u', 'i'}):

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')):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download