
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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?
In Python, you can check whether a string contains letters, numbers, or both using built-in string methods such as isalpha(), isdigit(), and isalnum(). You can also use loops or regular expressions for more customized checks.
Checking for Only Alphabets
The isalpha() method returns True if every character in the string is a letter (a-z or A-Z) and the string is not empty. It is useful for validating names or inputs that should contain only alphabets.
Example
In this example, we check if the string has only alphabets using the isalpha() method -
text = "HelloWorld" print(text.isalpha())
The string returns True since it contains only letters and no spaces or digits -
True
Checking for Only Numbers
The isdigit() method returns True if all characters in the string are numeric digits (0-9) and the string is not empty. It is commonly used to validate numerical input like age or ID numbers.
Example
In this example, we verify if the string consists of only numbers using the isdigit() method -
text = "12345" print(text.isdigit())
The result is True because the string contains only digits -
True
Checking for Either Alphabets or Numbers
To check if a string contains at least one letter or one digit, you can use a loop to go through each character or apply regular expressions. This is helpful when strings may contain a mix of character types.
Example: Using Loop and any() Function
In this example, we check for the presence of at least one letter or number using a loop and the any() function -
text = "abc123!" has_alpha = any(c.isalpha() for c in text) has_digit = any(c.isdigit() for c in text) print("Contains alphabet:", has_alpha) print("Contains digit:", has_digit)
Following is the output obtained -
Contains alphabet: True Contains digit: True
Example: Using Regular Expressions
Regular expressions uses pattern matching to check if alphabets, digits, or other character types are present within a string or not.
This example uses re.search() function to find matching patterns inside the string -
import re text = "code2024" if re.search(r"[A-Za-z]", text): print("Contains at least one alphabet") if re.search(r"\d", text): print("Contains at least one number")
We get the output as shown below -
Contains at least one alphabet Contains at least one number