Reputation: 41
so I've been assigned an assignment (obviously) to check if an input that a user has entered is formatted correctly, in the way AA99AAA (where A is a letter and 9 is a number from 0 to 9). So for the first character in the input, it would have to be a letter or python would return some sort of error and so on, you get the idea. I've got no clue where to start with this, I've tried looking around and haven't found anything - I guess I just don't know what it is I'm looking for. Any pointers would be greatly appreciated, thanks!
Upvotes: 1
Views: 4332
Reputation: 41
I finally did it! After about an hour...
So I used [] formatting and .isdigit/.isalpha to check each part of the code, like recommended above, however I did it in a slightly different way:
while True:
regNo = input("Registration number:")
if len(regNo) != 7:
print("Invalid Registration Number! Please try again")
elif regNo[:2].isdigit():
print("Invalid Registration Number! Please try again!")
elif regNo[2:4].isalpha():
print("Invalid Registration Number! Please try again!")
elif regNo[4:].isdigit():
print("Invalid Registration Number! Please try again!")
else:
break
Hopefully this helps anyone else who stumbles across this problem!
Upvotes: 1
Reputation: 259
To do this, you could split the string into 3 parts (the first group of letters, the numbers, and then the second group of letters). Then you can use s.isalpha()
and s.isnumeric()
.
For example:
while True:
c=input('Password: ')
if len(c)==7 and c[:2].isalpha() and c[2:4].isnumeric() and c[4:].isalpha():
break
else:
print('Invalid input')
print('Valid input')
Upvotes: 2
Reputation: 745
Could you provide more information regarding the question, is the example you have provided the format you are attempting to match? AA99AAA
, so 2-alpha, 2-numeric, 3-alpha?
There are two approaches off the top of my head you could take here, one would be to utilize regular expressions to match on something like [\w]{2}[\d]{2}[\w]{3}
, alternatively you could iterate through the string (recall that strings are character arrays).
For this approach you would have to generate substrings to isolate parts you are interested in. So..
for c in user_input[0:2]:
if c.isdigit:
print('Invalid Input')
for c in user_input[3:5]:
...
...
There are definitely more pythonic ways to approach this but this should be enough information to help you formalize a solution.
Upvotes: 1