Computer >> Computer tutorials >  >> Programming >> Python

How do I verify that a string only contains letters, numbers, underscores and dashes in Python?


You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$". 

example

import re
print(bool(re.match("^[A-Za-z0-9_-]*$", 'aValidString123--__')))
print(bool(re.match("^[A-Za-z0-9_-]*$", 'inv@lid')))

Output

True
False

You can also get this result by using Sets. Declare a set using the characters you want to allow and use the following code −

Example

from sets import Set
allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
validationString = 'inv@lid'
if Set(validationString).issubset(allowed_chars):
    print True
else:
    print False

Output

This will give you the result −

False