Check if a String Contains Only Alphanumeric Characters and Underscores in Python

Many guides still use re.match(r"^\w+$", s) to check if a string contains only alphanumeric characters and underscores in Python. It’s fine on easy input, but it lets a trailing newline through and accepts letters like é.

A tighter answer is re.fullmatch(r"[A-Za-z0-9_]+", s). It tests the whole string, and the character class allows only ASCII letters, digits and the underscore.

In this tutorial, I’ll show you how to check if a string contains only alphanumeric characters and underscores in Python four ways, and where each one disagrees. Every result below comes from Python 3.12.5.

Sample signup strings we’ll check

Say you run signup for a US online store and usernames may use only letters, digits and _. Save this list as signup_data.py; every example imports it:

usernames = [
    "emily_r2026",   # valid
    "mike-jones",    # hyphen
    "josé_88",       # accented letter
    "user٣",         # Arabic-Indic 3
    "2fast",         # leading digit
    "___",           # underscores only
    "",              # empty field
]

Watch the accented name, the Arabic-Indic digit and the empty field. For the opposite question, here’s how to check if a string contains any special character in Python.

Method 1: Check a string with re.fullmatch() and [A-Za-z0-9_] (Recommended)

Use this when your rule is plain ASCII: usernames, product SKUs, form fields. Here’s the code on the same sample list:

import re
from signup_data import usernames

ALLOWED = re.compile(r"[A-Za-z0-9_]+")

for name in usernames:
    ok = ALLOWED.fullmatch(name) is not None
    print(f"{name!r:15} {ok}")

Output:

'emily_r2026'   True
'mike-jones'    False
'josé_88'       False
'user٣'         False
'2fast'         True
'___'           True
''              False

Only emily_r2026, 2fast and ___ pass. The hyphen, the accent, the Arabic-Indic digit and the empty field all fail.

VS Code output of Python re.fullmatch checking signup usernames for only letters, digits and underscores
It’s an ASCII-only check, so the accented name fails.

How does this code work?

fullmatch() returns a match only when the pattern covers the whole string, so you don’t need ^ or $.

The + means one or more, so the empty field fails. Swap it for {3,20} and you get a length rule too, which is handy for real signup forms and product SKUs:

import re

USERNAME = re.compile(r"[A-Za-z0-9_]{3,20}")     # 3-20 characters
SKU = re.compile(r"[A-Z]{2}_[0-9]{4}_[A-Z]{3}")   # like TX_4471_BLK

print(bool(USERNAME.fullmatch("jo")), bool(USERNAME.fullmatch("emily_r2026")))
print(bool(SKU.fullmatch("TX_4471_BLK")), bool(SKU.fullmatch("tx_4471_blk")))

Output:

False True
True False

jo is too short, and the lowercase SKU fails because the pattern only allows [A-Z]. I used [0-9] instead of \d, since \d also matches non-ASCII digits.

Pro Tip: Compile the pattern once when you validate many rows. To clean bad input instead of rejecting it, see removing special characters from a string.

Method 2: Use \w+ for Unicode letters, digits and underscores

Reach for \w when international names are welcome. Same sample list, now with and without the re.ASCII flag:

import re
from signup_data import usernames

for name in usernames:
    uni = re.fullmatch(r"\w+", name) is not None
    asc = re.fullmatch(r"\w+", name, re.ASCII) is not None
    print(f"{name!r:15} unicode={uni!s:5}  ascii={asc}")

Output:

'emily_r2026'   unicode=True   ascii=True
'mike-jones'    unicode=False  ascii=False
'josé_88'       unicode=True   ascii=False
'user٣'         unicode=True   ascii=False
'2fast'         unicode=True   ascii=True
'___'           unicode=True   ascii=True
''              unicode=False  ascii=False
VS Code output of Python regex \w matching accented letters and Arabic-Indic digits unless re.ASCII is used
The two non-ASCII names flip to False with re.ASCII.

How does this code work?

In Python 3, str patterns are Unicode-aware: \w matches anything str.isalnum() accepts, plus _. So é and ٣ pass.

Adding re.ASCII shrinks \w to [a-zA-Z0-9_], so it matches Method 1. For letters-only rules, see checking if a string is alphabetic in Python.

Method 3: Use isalnum() after removing underscores

Don’t want a regex? isalnum() works, but it rejects _, so you remove underscores first. Same sample strings again:

from signup_data import usernames

for name in usernames:
    raw = name.isalnum()
    ok = name.replace("_", "").isalnum()
    strict = ok and name.isascii()
    print(f"{name!r:15} isalnum={raw!s:5}  no_={ok!s:5}  +ascii={strict}")

Output:

'emily_r2026'   isalnum=False  no_=True   +ascii=True
'mike-jones'    isalnum=False  no_=False  +ascii=False
'josé_88'       isalnum=False  no_=True   +ascii=False
'user٣'         isalnum=True   no_=True   +ascii=False
'2fast'         isalnum=True   no_=True   +ascii=True
'___'           isalnum=False  no_=False  +ascii=False
''              isalnum=False  no_=False  +ascii=False

The isalnum column shows the raw method rejecting emily_r2026. The no_ column runs it after removing underscores, and ___ still fails there because it leaves an empty string.

VS Code output of Python isalnum after replacing underscores, with an isascii check for ASCII-only usernames
Chaining isascii() gives an ASCII-only check without a regex.

How does this code work?

isalnum() needs at least one character, and every character must be a Unicode letter or number. The isdigit() method follows the same Unicode rules for digits.

Method 4: Check a string with isidentifier() (it can’t start with a digit)

isidentifier() answers a different question: is this a valid Python name? Here it is on four of the same usernames:

import keyword

for name in ["2fast", "josé_88", "user٣", "___"]:
    print(f"{name!r:10} {name.isidentifier()}")

print("class".isidentifier(), keyword.iskeyword("class"))

Output:

'2fast'    False
'josé_88'  True
'user٣'    True
'___'      True
True True

How does this code work?

It rejects 2fast and accepts josé_88 and user٣. It also says class is fine, so pair it with keyword.iskeyword(). More detail is in my isidentifier() method guide.

Why does a regex with $ accept a trailing newline?

This bug is why I switched to fullmatch(). In Python, $ matches at the end of the string or just before a final \n:

import re

name = "admin\n"                            # pasted from a spreadsheet

print(bool(re.match(r"^\w+$", name)))       # $ also matches before \n
print(bool(re.match(r"^\w+\Z", name)))      # \Z = true end of string
print(bool(re.fullmatch(r"\w+", name)))     # whole string must match

Output:

True
False
False
VS Code output showing Python re.match with $ accepting admin plus a newline while \Z and re.fullmatch reject it
Only the $ version lets the newline through.

That’s why you shouldn’t trust $ for validation. If a stray newline is acceptable, clean it first with the strip() function.

Which method should you use to check alphanumeric strings?

Method“_”é / ٣“”Best for
re.fullmatch(r"[A-Za-z0-9_]+", s)YesNoFalseUsernames, SKUs
re.fullmatch(r"\w+", s)YesYesFalseInternational names
s.replace("_", "").isalnum()YesYesFalseNo-regex checks
s.isidentifier()YesYesFalseVariable-like names

I’d pick Method 1 for anything a US form stores, and Method 2 when names come from everywhere.

Things to keep in mind when you check alphanumeric strings

  • isalnum() and \w+ both reject ""; use * if an empty field is allowed.
  • \w and isalnum() are Unicode-aware; add re.ASCII or isascii() for ASCII only.
  • $ allows one trailing newline; use fullmatch() or \Z.
  • isidentifier() rejects a leading digit but not keywords.

For more string checks, try these next: