How do I check if a string has alphabets or numbers in Python?



Python String class has a method called isalnum() which can be called on a string and tells us if the string consists only of alphanumerics or not. You can call it in the following way:

print( '123abc'.isalnum())

OUTPUT

True
print('123#$%abc'.isalnum())

OUTPUT

False

You can also use regexes for the same result. For matching alpha numerics, we can call the re.match(regex, string) using the regex: "^[a-zA-Z0-9]+$". For example,

import re
print(bool(re.match('^[a-zA-Z0-9]+$', '123abc')))

OUTPUT

True
import re
print(bool(re.match('^[a-zA-Z0-9]+$', '123abc#$%')))

OUTPUT

False

re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().


Advertisements