
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I verify that a string only contains letters, numbers, underscores and dashes in Python?
To verify that a string contains only letters, numbers, underscores, and dashes in Python -
- Use re.fullmatch() function with a pattern like [A-Za-z0-9_-]+ for regex-based checking.
- Use set comparison with all() function for simple logic-based validation.
Many systems restrict input to certain characters for security or formatting reasons. In this case, the allowed characters are alphabets (A-Z, a-z), digits (0-9), underscores (_), and hyphens (-).
Using Regular Expressions
The re module in Python allows you to define patterns to validate strings. You can use re.fullmatch() function to check if the entire string matches a specific pattern, such as allowing only letters, digits, underscores, or dashes.
Example
In the following example, we use re.fullmatch() function with a Regex pattern that matches the entire string -
import re def is_valid(text): return re.fullmatch(r"[A-Za-z0-9_-]+", text) is not None print(is_valid("User_123-Name")) # Valid print(is_valid("Invalid@Name")) # Invalid
Here, the pattern [A-Za-z0-9_-]+ ensures that all characters belong to the allowed set -
True False
Using Set Comparison
Set comparison checks if all characters in the string are part of a predefined set of valid characters like letters, numbers, underscores, or dashes. It is a simple way to validate custom rules without regular expressions.
Example
In this example, we compare characters with a predefined set -
def is_valid(text): allowed = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") return all(char in allowed for char in text) print(is_valid("Safe_String-42")) # Valid print(is_valid("Oops!")) # Invalid
This method gives you full control over character rules and works without importing external modules -
True False