Python – Check if String contains any Number
We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = “Hello123” since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = “HelloWorld” since it has no digits the output should be False.
Using any() and isdigit():
any() function in Python returns True if any element of an iterable evaluates to True and when combined with isdigit(), it can be used to check if any character in a string is a digit.
s = "abc123"
res = any(char.isdigit() for char in s)
if res: # If 'res' is True, it means there is at least one digit in the string
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- any(char.isdigit() for char in s) uses a generator expression to check if any character in the string s is a digit.
- isdigit() method returns True for digits and any() returns True if any character satisfies the condition.
Using a for loop:
A for loop can be used to iterate through each character in a string and check if any character is a digit using isdigit(). If a digit is found, a flag is set, and the result is displayed.
s = "abc123"
# Flag to track if number is found
flag = False
# Loop through each character and check if it's a digit
for char in s:
if char.isdigit():
flag = True
break
if flag:
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- if char.isdigit() checks if the current character char is a digit.
- If a digit is found, flag = True sets the flag to True and break exits the loop early to stop further checks.
Using Regular Expressions:
Regular expressions (regex) in Python offer a powerful way to search for patterns within strings. The re module provides functions like re.search() to check if a string contains specific patterns such as digits. By using a regex pattern like \d, you can easily detect if any digit exists in the string.
import re
s = "abc123"
# Check if the string contains any digit
res = bool(re.search(r'\d', s))
if res:
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- re.search(r’\d’, s) searches for the first digit (\d) in the string s.
- bool(re.search(r’\d’, s)) converts the result to True if a digit is found otherwise False.