
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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().
- Related Articles
- Check if a string has m consecutive 1s or 0s in Python
- How do I check if a Python variable exists?
- How do we check in Python whether a string contains only numbers?
- How do I know if Python has pandas installed?
- Check if a string contains only alphabets in Java using Regex
- How do I check if a column is empty or null in MySQL?
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a string contains only alphabets in Java using ASCII values
- Check if a string is Isogram or not in Python
- Check if a binary string has a 0 between 1s or not in C++
- Python - Check if a given string is binary string or not
- How to check if string or a substring of string ends with suffix in Python?
- How to check if string or a substring of string starts with substring in Python?
- Check if the String has only unicode digits or space in Java
- How do you check if a widget has a focus in Tkinter?

Advertisements