Open In App

Verify that a string only contains letters, numbers, underscores and dashes – Python

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a string and our task is to verify whether it contains only letters, numbers, underscores (_), and dashes (-). This kind of check is useful for validating usernames or formatted inputs. For example, a string like “G33ks_F0r-G3eks” should pass the validation, while a string like “Hello@123” should fail because it contains the @ symbol.

Using regular expression

There is a function in the regular expression library(re) that compares two strings for us. re.match(pattern, string) is a function that returns an object, to find whether a match is find or not we have to typecast it into boolean.

Python
import re

p= "^[A-Za-z0-9_-]*$" # pattern
s= "G33ks_F0r_Geeks"

res = bool(re.match(p, s))
print(res)

Output
True

Explanation: The pattern ^[A-Za-z0-9_-]*$ ensures the entire string contains only letters, digits, underscores, or dashes. re.match() checks the string against this pattern, and bool() returns True if it matches, otherwise False.

Using str.isalnum()

We can use str.isalnum() method to check if all characters in a string are alphanumeric. By adding simple checks for underscores and dashes, we efficiently validate strings with mixed characters.

Python
s= "G33ks_F0r_Geeks"
res= all(c.isalnum() or c in "_-" for c in s)
print(res)

Output
True

Explanation: all() returns True if every character in the string is a letter, digit, underscore or dash. isalnum() checks for letters and digits, c in “_-” allows underscores and dashes.

Using str.replace()

This method removes underscores and dashes from the string using replace(), then checks if the remaining characters are only letters and numbers with a regular expression.

Python
import re
s= "G33ks_F0r_Geeks"

b= s.replace("_", "").replace("-", "") # cleaned string
res = bool(re.match("^[A-Za-z0-9]*$", b))
print(res)

Output
True

Explanation: string s is first cleaned by removing underscores and dashes using replace(). The resulting string b is then checked with the pattern ^[A-Za-z0-9]*$ to ensure it contains only letters and digits. re.match() verifies this.

Using Loop

This method iterates through each character and checks whether it’s a letter, digit, underscore, or dash using basic conditions. If an invalid character is found, it stops early for efficiency.

Python
s = "G33ks_F0r-G3eks"
res = True

for c in s:
    if not (c.isalnum() or c == '_' or c == '-'):
        res = False
        break
print(res)

Output
True

Explanation: This loop iterates through each character in the string s and checks if it’s a letter, digit, underscore or dash using isalnum() and direct comparisons. If any character doesn’t meet these conditions, res is set to False and the loop breaks.



Next Article

Similar Reads