Reputation: 154
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
Upvotes: 0
Views: 1870
Reputation: 1057
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 :)
Upvotes: 0
Reputation: 4341
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
[A-Z]
-----> Match one capital letter
[a-z]{2}
--> Match two lowercase letters
\d{3}
-----> Match 3 digits
$
---------> Assert position at end of string
Upvotes: 2