简体   繁体   中英

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 MU and I. can anyone give me a hand?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM