

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Check if a string has m consecutive 1s or 0s in Python
- How do I know if Python has pandas installed?
- How do I check if a Python variable exists?
- How do I check if a column is empty or null in MySQL?
- Check if a binary string has a 0 between 1s or not in C++
- How do you check if a widget has a focus in Tkinter?
- Check if a string has white space in JavaScript?
- Check if a string contains only alphabets in Java using Regex
- Check if the String has only unicode digits or space in Java
- How do we check in Python whether a string contains only numbers?
- Check if a string is Isogram or not in Python
- Python - Check if a given string is binary string or not
- 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 contains numbers in MySQL?
Advertisements