0

I need to write an algorithm that validates a player's username and checks to see if the name is registered in an external text file.

playerName = input('Please enter a player name')

How do I restrict the user to only being able to enter letters and numbers?

Simimic
  • 132
  • 2
  • 7
  • you can use regex and if statement to check that – icecube Mar 14 '21 at 20:27
  • use `playerName.isalnum()` to check the user typed alphabets or numbers. For more details, see example - https://www.w3schools.com/python/ref_string_isalnum.asp – Joe Ferndz Mar 14 '21 at 20:40
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo Mar 14 '21 at 21:37

2 Answers2

2

You cannot restrict what the user can type (at least with input) but you can use a while loop to repeat the input request until user gets it right

peer
  • 4,171
  • 8
  • 42
  • 73
0

As @peer said, you can use a regex in a while loop. There is no way to do it with input command.

Exemple of code:

import re
 
playerName = '_'
    
while(not re.match("^[A-Za-z0-9]*$", playerName)):
    playerName = input('Please enter a player name (Only letters and numbers)')
    
print("PlayerName: ", playerName)

EDIT

As @Joe Ferndz wrote in comment, you can use isalnum() method to check if your playerName is alphanumeric, so you don't even need to use regex

playerName = '_'
    
while(not playerName.isalnum()):
    playerName = input('Please enter a player name (Only letters and numbers)')
    
print("PlayerName: ", playerName)
Maaz
  • 2,405
  • 1
  • 15
  • 21