discord1
discord1

Reputation: 31

checking if string only contains certain letters in Python

i'm trying to write a program that completes the MU game https://en.wikipedia.org/wiki/MU_puzzle

basically i'm stuck with ensuring that the user input contains ONLY M, U and I characters.

i've written

alphabet = ('abcdefghijklmnopqrstuvwxyz')

string = input("Enter a combination of M, U and I: ")

if "M" and "U" and "I" in string:
    print("This is correct")
else:
    print("This is invalid")

i only just realised this doesnt work because its not exclusive to just M U and I. can anyone give me a hand?

Upvotes: 1

Views: 3268

Answers (3)

B. M.
B. M.

Reputation: 18628

A simple program that achieve your goal with primitive structures:

valid = "IMU"
chaine = input ('enter a combination of letters among ' + valid + ' : ')

test=True
for caracter in chaine:
    if caracter not in valid:
        test = False

if test :        
    print ('This is correct')    
else:    
    print('This is not valid')

Upvotes: 0

Keatinge
Keatinge

Reputation: 4341

If you're a fan of regex you can do this, to remove any characters that aren't m, u, or i

import re
starting = "jksahdjkamdhuiadhuiqsad"
fixedString = re.sub(r"[^mui]", "" , starting)

print(fixedString)
#output: muiui

Upvotes: 0

kindall
kindall

Reputation: 184121

if all(c in "MIU" for c in string):

Checks to see if every character of the string is one of M, I, or U.

Note that this accepts an empty string, since every character of it is either an M, I, or a U, there just aren't any characters in "every character." If you require that the string actually contain text, try:

if string and all(c in "MIU" for c in string):

Upvotes: 2

Related Questions