简体   繁体   中英

How can I set up a format check in python 3 if i want the data input by user to be of a particular format?

So basically I want to prompt user for input and this input should follow a strict order which is precisely in the sequence "One upper case letter followed by 2 lower case letters followed by 3 numerals or integars" But the code i've written gives an error and this error only occurs when a correct format input is made, otherwise no errors while running it. What am i doing wrong and how can get this done? (screens attached) enter image description here

enter image description here

This is exactly the kind of thing regex was intended for

^[A-Z][a-z]{2}\d{3}$


Python implementation:

while 1:
    inputString = input()
    if re.match(r"^[A-Z][a-z]{2}\d{3}$", inputString):
        print("Input accepted")
        break
    else:
        print("Bad input, please try again")


Output:

Aa123      #missing one lowercase
Bad input, please try again
Aaa22      #missing one integer
Bad input, please try again
aaa123     #missing one capital
Bad input, please try again
Aaa123     # 1 capital, 2 lower, 3 integers
Input accepted


How the regex works

$ ---------> Assert position at start of the string
[AZ] -----> Match one capital letter
[az]{2} --> Match two lowercase letters
\\d{3} -----> Match 3 digits
$ ---------> Assert position at end of string

In the Validation of the integer part, You are converting it into a integer and trying to make a string method call on it. Try to keep it simple

userID[3:5].isdigit()

would be enough. But the Best way to do this Validation is to go for Regular Expressions. And I feel you also need to check the length of the string so :

def ValidateUserID(u):
    result = False
    if u[0] == u[0].upper() and u[1:2] == u[1:2].lower() and u[3:5].isdigit() and len(u) == 6:
        result = True
    return result

Hope it helps. Happy Coding :)

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