How to check if string contains any number in Python

Given a String, check if it contains any number.

Input : test_str = ‘geeks4g2eeks’
Output : True
Explanation : Contains 4 and 2.

Input : test_str = ‘geeksforgeeks’
Output : False
Explanation : Contains no number.

Method #1 :  Using any() + isdigit()

The combination of the above functions can solve this problem. Here, we use isdigit() to check for digits and any() to check for any occurrences.

 

# Python3 code to demonstrate working of
# Check if string contains any number
# Using isdigit() + any()

# initializing string
test_str = 'geeks4geeks'

# printing original string
print("The original string is : " + str(test_str))

# using any() to check for any occurrence
res = any(chr.isdigit() for chr in test_str)
	
# printing result
print("Does string contain any digit ? : " + str(res))

Output

The original string is : geeks4geeks
Does string contain any digit ? : True

Method #2 : Using next() + generator expression + isdigit()

This is another way to accomplish this task. This is recommended for larger strings, iterations in cheap generators, but the construction is usually inefficient.

# Python3 code to demonstrate working of
# Check if string contains any number
# Using isdigit() + next() + generator expression

# initializing string
test_str = 'geeks4geeks'

# printing original string
print("The original string is : " + str(test_str))

# next() checking for each element, reaches end, if no element found as digit
res = True if next((chr for chr in test_str if chr.isdigit()), None) else False
	
# printing result
print("Does string contain any digit ? : " + str(res))

Output

The original string is : geeks4geeks
Does string contain any digit ? : True

 

Submit Your Programming Assignment Details