hi all trying to ask for username and only letters or numbers or _ can be used. if anything else is provided i need to ask again. this is what i have so far but when i try to run it just keeps going instead of completing. so after the first question, if i enter username like "jack" it should just print username: jack, but instead it just keeps asking the second question in the code 'Please enter a username(only letters and numbers) how do i fix this?
Username = input ("What is your username?")
while Username != "^[A-Za-z0-9]*$":
Username = input('Please enter a username(only letters and numbers)')
print("Username: ", Username)
CodePudding user response:
There can be two ways.
- To cycle through the string and check if each character belongs to the range of letters or numbers. Though this is not advised as it is time and memory consuming.
- Using
str.isalnum()
. This is easy short and better than the previous.
Code:
Username = input ("What is your username?")
while not Username.replace('_', '').isalnum(): #Edit: Removed _ as an invalid character
Username = input('Please enter a username(only letters and numbers)')
print("Username: ", Username)
CodePudding user response:
A small modification to this https://stackoverflow.com/a/71506891/18248018 answer would be to substitute the line
while not Username.replace('_', '').isalnum():
leaving everything else the same.
This would allow the username to still contain underscores, if this is your intent.
.replace(old, new)
returns a new string (leaving the original one unchanged) with all instances of the substring old
replaced with string new
. This means that the modified line of code above calls .isalnum()
on a string equivalent to the Username input stripped of underscores, and checks whether all the remaining characters are alphanumeric.
Otherwise, .isalnum()
will reject input containing underscores.