How to check if a string is alphanumeric in python:
If a string contains alphabet or numbers, then it is called alphanumeric. In python, it is easy to find out if a string is alphanumeric or not. Python string provides a method called isalnum that can be used to check that.
In this post, we will learn how to use use isalnum with examples.
Definition of isalnum:
isalnum is defined as below:
str.isalnum()
It returns one boolean value. It is True if all characters in the string are alphanumeric. Else, it returns False. For an empty string, it returns False.
Example of isalnum:
Let’s try isalnum with different strings:
str_arr = ['a', '', 'abc', 'abc123', '123', 'abc#$%', 'hello 123', 'hello123']
for item in str_arr:
print('{} is : {}'.format(item, item.isalnum()))
Here,
- str_arr is a list of strings and we are iterating through its items using a for-in loop.
- Inside the loop, we are printing the string and the result of isalnum.
It will give the below output:
a is : True
is : False
abc is : True
abc123 is : True
123 is : True
abc#$% is : False
hello 123 is : False
hello123 is : True
As you can see, even if the string contains a space, it is not considered a alphanumeric string. For example, hello 123 includes one space in the middle and it prints False for it.
You might also like:
- Python program to check if the characters in a string are sequential
- Python program to add items to a list without using append()
- Python program to capitalize all characters of a string without using inbuilt functions
- Python program to get the string between two substrings
- Python string join() method explanation with example
- How to copy string in python