Verify that a string only contains letters, numbers, underscores and dashes - Python
Last Updated :
07 Apr, 2025
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)
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)
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)
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)
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.
Similar Reads
Check Whether String Contains Only Numbers or Not - Python We are given a string s="12345" we need to check whether the string contains only number or not if the string contains only number we will return True or if the string does contains some other value then we will return False. This article will explore various techniques to check if a string contains
3 min read
Python program to calculate the number of digits and letters in a string In this article, we will check various methods to calculate the number of digits and letters in a string. Using a for loop to remove empty strings from a list involves iterating through the list, checking if each string is not empty, and adding it to a new list.Pythons = "Hello123!" # Initialize cou
3 min read
Python | Ways to check if given string contains only letter Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let's discuss a few methods to complete the task. Method #1: Using isalpha() method Python3 # Python code to demonstrate # to find whether string contains # only letters # Initialising string
3 min read
Python program to check if a string has at least one letter and one number The task is to verify whether a given string contains both at least one letter (either uppercase or lowercase) and at least one number. For example, if the input string is "Hello123", the program should return True since it contains both letters and numbers. On the other hand, a string like "Hello"
3 min read
Remove All Characters Except Letters and Numbers - Python In this article, weâll learn how to clean a string by removing everything except letters (AâZ, aâz) and numbers (0â9). This means getting rid of:Special characters (@, #, !, etc.)Punctuation marksWhitespaceFor example, consider a string s = "[email protected]", after removing everything except the numbers
2 min read
Python - Test String in Character List and vice-versa Given a String, check if it's present in order in the character list and vice versa. Input : test_str = 'geeks', K = ['g', 'e', 'e', 'k', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] [ String in Character list ] Output : True Explanation : geeks is present in list , starting from 7th index till end. Inpu
3 min read