Q:

Checking each character in a string with regex - python

I want to check a string and confirm it only has upper or lowercase alphabetical characters aswell as underscores.
I have this so far but I am getting errors
import re

def addPlayer():
    print("\nEnter the players name:")
    playerName = input()

    for x in range(len(playerName)):
        if re.match("[a-zA-Z_]", x):
            return
        else:
            print("Error: Please enter a valid name.")
            addPlayer()

Traceback (most recent call last):
    File "player.py", line 9, in addPlayer
    if re.match("[a-zA-Z_]", x):
  File "c:.....Python\Python38-32\lib\re.py", line 189, in match
    return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object

A:

You can check your entire username at once by checking that all the characters in the string are in the character class [A-Za-z_] i.e.
import re

def addPlayer():
    print("\nEnter the players name:")
    playerName = input()

    if not re.match(r'^[A-Za-z_]+$', playerName):
        print("Error: Please enter a valid name.")
        addPlayer()

