Python – Check if string contains any number

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 above functions can be used to solve this problem. In this, we check for number using isdigit() and check for any occurrence using any().



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output

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

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

This is yet another way in which this task can be performed. This is recommended in cases of larger strings, the iteration in generator is cheap, but construction is usually inefficient.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.