0

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")

2 Answers 2

3

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')):
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

That definitely works but could you please explain to me exactly what the code after print does. for me it looks like it is looking for only m i and u in the string and if not then it stuff up but for example what does the word all do?
I edited my answer to answer this. I'm leaving it for pedagogical purposes but I prefer sberry's solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.