How to check if a string is alphanumeric in Python?

PythonServer Side ProgrammingProgramming

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:

>>> '123abc'.isalnum()
True
>>> '123#$%abc'.isalnum()
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,

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

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

raja
Published on 08-Dec-2017 12:09:25
Advertisements