Summary: In this programming tutorial, we will learn different ways to check if the given string has any character as a number in Python.
Method 1: Using for loop with str.isdigit()
isdigit() is a built-in string method in Python that returns
True if all the characters of the given strings are integer.
To check whether the given string has integers, we will loop through its characters using a for loop and use the
isdigit method on each character.
>>> string = 'python123' >>> for x in string: ... if x.isdigit(): ... print('String has integers.') ... break String has integers
Alternatively, we can rewrite the same code using any() function as follows:
>>> string = 'python123' >>> result = any(x.isdigit() for x in string) >>> print(result) True
Method 2: Using map() with str.isdigit()
map(function, iterator) functions in Python apply the given function to each item of the given iterator and returns the resultant iterator.
If we apply
str.isdigit to each character of the string using the
map function, we will get the resultant iterator (i.e. map object) that may contain True as one of its items, if any of the characters in the given string is an integer.
>>> string = 'python123' >>> result = any(map(str.isdigit, string)) >>> print(result) True
Method 3: Using Regular Expression
The fastest way to check if a string contains numbers is through regular expressions.
re.search(r'\d', string) function looks for the pattern
r'\d' (i.e. integer) in the given string and returns the match object if a match is found. Otherwise, it returns
If the match object returned by the search function is not
None, the string has numbers.
>>> import re >>> >>> string = 'ak5647' >>> match = re.search(r'\d', string) >>> if match: ... print('Yes') ... else: ... print('No') Yes
We can make this process more efficient and faster by using re.compile() on the pattern before the
re.search() function (when the expression will be used several times in a single program).
In that case, we call the
search method on the object returned by the
re.compile function with the string parameter.
>>> import re >>> >>> string = 'ak5647' >>> >>> re_obj = re.compile(r'\d') >>> match = re_obj.search(string) >>> >>> if match: ... print('Yes') ... else: ... print('No') Yes
In conclusion, we can easily check for the numbers in a string in Python by using the
map() function, and regular expression. However, using regular expression is efficient in the case of larger strings.