简体   繁体   中英

Python limiting character input

I'm trying to only allow the letters a, b or c in an input for a .dat file in a Python program (code below), but I'm having difficulty getting the program to do this correctly.

varClass = "class" + input("Which class are you in? [A/B/C]: ").lower() + ".dat"
if not re.match("^[a-c]*$", varClass):
    print("Enter the correct class number")

This is what I have already, but it still continues to run even after an incorrect character has been entered.

varClass = "class" + input("Which class are you in? [A/B/C]: ").lower() + ".dat"
if not re.match("^class[a-c]\.dat$", varClass):
    print("Enter the correct class number")

Your match will always return false as match matches from beginning and you have class at the beginning.

Take the input first, check it then add class and .dat , you have already added class and .dat before you check the input, adding then checking is doing things a bit backwards:

allowed = {"a","b","c"}
inp =  input("Which class are you in? [A/B/C]: ").lower()
if not allowed.issuperset(inp):
     print("Enter the correct class number")
else:
     var = "class{}.dat".format(inp)

If you have certain specific letter combinations you will have to add those in the set and check:

    inp =  input("Which class are you in? [A/B/C]: ").lower()
    if inp.lower() not in {"ab","ac"}:
         print("Enter the correct class number")
    else:
         var = "class{}.dat".format(inp)

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