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

How to check if a string only contains certain characters in Python?


You can check if a string only contains certain characters result by using Sets. Declare a set using the characters you want to allow. For example if we want to check if a string only contains 1, 2, 3 and 4, we can use −

Example

from sets import Set
allowed_chars = Set('1234')
validationString = '121'
if Set(validationString).issubset(allowed_chars):
    print True
else:
    print False

Output

This will give you the result −

True

You can also use regexes for the same result. For matching only 1, 2, 3 and 4, we can call the re.match(regex, string) using the regex: "^[1234]+$". 

 example

import re
print(bool(re.match('^[1234]+$', '123abc')))
print(bool(re.match('^[1234]+$', '123')))

Output

False
True

 Keep in mind that regexes have special uses for some characters and hence require escaping them. re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().