In this tutorial, I will explain how to verify that a string only contains letters, numbers, and underscores in Python. As a Python developer working on a project for a US-based company, I recently faced an issue where I needed to ensure that user-provided strings only contained alphanumeric characters and underscores. After researching and testing different methods, I found several effective solutions that I will share with you in this article.
Method 1. Use Regular Expressions (Regex)
One of the most important tools for string validation in Python is regular expressions (regex). With regex, you can define a pattern that the string must match. In this case, we want to allow only alphanumeric characters and underscores.
Here’s an example of how to use regex to check if a string contains only alphanumeric characters and underscores:
import re
def is_alphanumeric_underscore(string):
pattern = re.compile(r'^[\w_]+$')
return bool(pattern.match(string))
username1 = "John_Doe42"
username2 = "Jane-Doe"
print(is_alphanumeric_underscore(username1))
print(is_alphanumeric_underscore(username2)) Output:
True
FalseI have executed the above code and added the screenshot below.

In this code, we define a function called is_alphanumeric_underscore that takes a string as input. We create a regex pattern using re.compile(r'^[\w_]+$'). The \w metacharacter matches any alphanumeric character (letters and numbers), and the underscore _ is included explicitly. The ^ and $ anchors ensure that the entire string matches the pattern.
Read How to Reshape an Array in Python Using the NumPy Library?
Method 2. Use the isalnum() Method
Python provides a built-in method called isalnum() that checks if a string contains only alphanumeric characters. However, it does not include underscores. To work around this, we can replace the underscores with an empty string and then use isalnum().
Here’s an example:
def is_alphanumeric_underscore(string):
return string.replace("_", "").isalnum()
username1 = "John_Doe42"
username2 = "Jane-Doe"
print(is_alphanumeric_underscore(username1))
print(is_alphanumeric_underscore(username2)) Output:
True
FalseI have executed the above code and added the screenshot below.

In this approach, we define the is_alphanumeric_underscore function that takes a string as input. We first replace any underscores with an empty string using string.replace("_", ""). Then, we call the isalnum() method on the resulting string, which returns True if the string contains only alphanumeric characters.
Check out How to Save an Array to a File in Python?
Method 3. Use a Loop and Character Comparison
Another way to check if a string contains only alphanumeric characters and underscores is to iterate through each character in the string and check if it is alphanumeric or an underscore.
Here’s an example:
def is_alphanumeric_underscore(string):
for char in string:
if not (char.isalnum() or char == "_"):
return False
return True
username1 = "John_Doe42"
username2 = "Jane-Doe"
print(is_alphanumeric_underscore(username1))
print(is_alphanumeric_underscore(username2))Output:
True
FalseI have executed the above code and added the screenshot below.

In this solution, we define the is_alphanumeric_underscore function that takes a string as input. We use a for loop to iterate through each character in the string. For each character, we check if it is alphanumeric using the isalnum() method or if it is an underscore using char == "_". If any character fails this condition, we immediately return False. If the loop completes without returning False , it means all characters are alphanumeric or underscores, so we return True.
Read Is Python an Object-Oriented Language?
Performance Considerations
When dealing with large strings or performing frequent string validations, performance becomes an important factor. Among the three methods discussed, regular expressions and the isalnum() method is generally faster than iterating through each character in the string.
However, the performance difference may not be significant for small to medium-sized strings. It’s always a good idea to profile your code and choose the method that best fits your specific use case and performance requirements.
Check out Difference Between is and == in Python
Conclusion
In this tutorial, we explored three different methods to check if a string contains only alphanumeric characters and underscores in Python. Regular expressions provide a concise and flexible way to define complex patterns for string validation. isalnum() method, combined with replacing underscores, offers a simple and readable solution. Looping and character comparison give more fine-grained control but may be slower for large strings.
You may also like to read:
- How to Use the ceil() Function in Python?
- How to Use the Python pop() Function?
- What Is the Best Way to Learn Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.