Whether you're building a verification script for user input, a login form that requests users to include a character in a password - checking whether a string contains a character isn't an uncommon operation.
In this tutorial - we'll take a look at the many ways you can check whether a string contains a digit/number in Python, including a benchmark for the most efficient approach in the end.
Check If String Contains Number in Python
There's a multiple ways to check whether a character is a number [
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
2, str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3, str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
4], which you can couple with a for-loop, to check for at least a single positive hit. Alternatively, you can use Regular Expressions as general pattern matchers, which are flexible, powerful and designed to be applied to large corpuses of text. Finally - you can always str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
5 each character given a conditional statement, and return str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6 is str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
7 of them result in str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6.Choosing between these should take into consideration the efficiency of the methods, verbosity and coding style, as well as upstream or downstream tasks associated with the operation.
Check if String Contains Number with ord[]
The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
2 function takes a character and returns its ASCII value:The ASCII value of
String is whole numeric? True
String is whole numeric? False
0 is 48, and the ASCII value of String is whole numeric? True
String is whole numeric? False
1 is 57. Any number between these, will by extension, have an ASCII value between 48 and 57. Now to check if the string has any number, we will traverse the whole input string and check the ASCII value of each character, if the ASCII value is more than 47 and less than 58, it means it's a number, and we will return str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6:input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
ascii_code = ord[ch]
if 47 < ascii_code < 58:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
This results in:
Yes, the string contains a number.
Check if String Contains Number with isnumeric[]
The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3 function returns str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6 if the input string contains only numbers, otherwise, it returns String is whole numeric? True
String is whole numeric? False
5:str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
This results in:
String is whole numeric? True
String is whole numeric? False
Note: The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3 function will not behave as you may expect for negative or float numbers. If we pass a string with only negative or float numbers, it will return String is whole numeric? True
String is whole numeric? False
5, because the String is whole numeric? True
String is whole numeric? False
8 and String is whole numeric? True
String is whole numeric? False
9 characters associated with negative numbers and floats are indeed, not numbers.Though, since characters are just strings of length 1 in Python - you can iterate through characters and use
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3 to check whether they're a number:input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isnumeric[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
Check if String Contains Number with isdigit[]
The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
4 function checks whether all the characters in a string are digits. If yes - it returns str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6, and if not, it returns String is whole numeric? True
String is whole numeric? False
5. Again, since characters are just strings of length 1 in Python - this method can be used in a loop for each character:input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isdigit[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
Note: The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
4 method only behaves in the same manner as str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3, and if you pass a string containing a float or a negative number to it, String is whole numeric? True
String is whole numeric? False
5 is returned due to the special characters not being numbers. On a character-level, though, if as long as one str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6 value is enough to determine whether the string contains a number - it's applicable.Difference Between isnumeric[] and isdigit[]?
So, what's the difference between
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3 and str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
4? While we're at it - what about input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isdigit[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
0?
3 checks whether any character is a unicode representation of a numeric value [which includes roman numeric representations, superscripts, subscripts and fractions]str1 = "918" print["String is whole numeric?", str1.isnumeric[]] str2 = "The meaning of the universe is 42" print["String is whole numeric?", str2.isnumeric[]]
4 checks whether any character is a unicode digit [which doesn't innclude roman numeric representations, but does include super/subscripts and fractions]str1 = "918" print["String is whole numeric?", str1.isnumeric[]] str2 = "The meaning of the universe is 42" print["String is whole numeric?", str2.isnumeric[]]
0 checks whether any characters is a decimal digit [which would returninput_string = "My name is Satyam & I am 22 yrs old" flag = False for ch in input_string: if ch.isdigit[]: flag = True break if flag: print["Yes, the string contains a number."] else: print["No, the string does not contain a number."]
5 for anything that's notString is whole numeric? True String is whole numeric? False
5 in base 10]input_string = "My name is Satyam & I am 22 yrs old" flag = False for ch in input_string: if ch.isdigit[]: flag = True break if flag: print["Yes, the string contains a number."] else: print["No, the string does not contain a number."]
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3 is the most broad method, while input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isdigit[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
0 is the most narrow between the three.Check if String Contains Number with map[] and any[]
The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
5 function executes the provided function for each element of the iterable passed in the map function. Each element of an iterable is passed to the function as a parameter:map[function, iterable]
The
input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isdigit[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
9 is executed for every item of the map[function, iterable]
0. This allows for very flexible and powerful logic, only bounded by the extensiveness of the input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isdigit[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
9 you call on the input! The method returns a map[function, iterable]
2 instance, which can be easily turned into other collections such as a list or set.We can write a function that returns a boolean representing whether a character is a number, and the
5 call will thus result in a list of boolean values.str1 = "918" print["String is whole numeric?", str1.isnumeric[]] str2 = "The meaning of the universe is 42" print["String is whole numeric?", str2.isnumeric[]]
The
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
7 returns str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6 if any element of the passed iterable is str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
6, otherwise, it returns String is whole numeric? True
String is whole numeric? False
5.Stringing these two together - we can create a high-level, short script and abstract the for-loop away:
This results in:
Is there a number present? True
If your function is a one-liner - there's no need to extract it as a named function. You can write an anonymous lambda function instead for brevity's sake:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
input_string = "My name is Satyam & I am 22 yrs old"
contains_number = any[list[map[lambda ch: ch.isdigit[], input_string]]]
print["Is there any number present?", contains_number]
This also results in:
Is there any number present? True
Check if String Contains Number in Python with Regular Expressions
Regular Expressions are search patterns designed to be matched against input text. They're flexible and given their nature - you can write an arbitrary number of expressions for the same pattern to search for, as well as cover any tractible pattern you can think of.
Python's
map[function, iterable]
8 module is used to write, compile and match text against regular expressions. It exposes various methods, such as map[function, iterable]
9 which matches whether a string begins with a pattern, Is there a number present? True
0 which finds the first occurrence of possibly many matches in a string, and Is there a number present? True
1 which checks for all occurences.Note: All three methods accept a
Is there a number present? True
2 and Is there a number present? True
3 argument and run a search for the Is there a number present? True
2 in the Is there a number present? True
3 string.The pattern that identifies a digit is
Is there a number present? True
6:Yes, the string contains a number.
0The
Is there a number present? True
0 method returns a Is there a number present? True
8 object, containing the match found and the starting and ending indices:Yes, the string contains a number.
1The object is can be evaluated to a boolean value based on whether it's a
Is there a number present? True
8 object or input_string = "My name is Satyam & I am 22 yrs old"
contains_number = any[list[map[lambda ch: ch.isdigit[], input_string]]]
print["Is there any number present?", contains_number]
0. This results in:Yes, the string contains a number.
2Unlike the
Is there a number present? True
0 method, the Is there a number present? True
1 method returns all occurrences of the pattern instead of just the first one:Yes, the string contains a number.
3This results in:
Yes, the string contains a number.
2Benchmarking
What about the performance? If you extract the logic and trim the unnecessary parts, limiting the methods to returning the result only, you can easily benchmark them one against the other on the same input:
Yes, the string contains a number.
5This results in:
Yes, the string contains a number.
6Generally the for-loop approaches run in around the same time, with little overhead from the specific methods. Lambda with
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
7 is defacto the slowest [a lot of reduntant operations, due to converting a list to a list and then reducing it], while Regular Expressions had the fastest runtime with the lowest variance around it [they're consistently fast].However, on longer input texts, the time complexities on each of the different approaches get emphasized, especially depending on the number of matched digits [whether digits are common or not]:
The first string generates a random sequence with about an equal number of digits and characters, while the latter is a character-only string with a single digit in the end [worst time complexity]:
Yes, the string contains a number.
7Yes, the string contains a number.
8Yes, the string contains a number.
9str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
0str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
1With a low number of hits - Regular Expressions are the most performant. With many hits, the lambda function approach is the most performant, and it retains its time complexity regardless of whether the input has many hits or one. The main downside [reduntant computation when hit rate is low] is turned into its main strength as redundancy makes it robust to input.
Conclusion
In this tutorial, we took a look at multiple ways to check whether a string in Python contains at least one character. We've taken a look at the
str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
2, str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
3, str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
4 and input_string = "My name is Satyam & I am 22 yrs old"
flag = False
for ch in input_string:
if ch.isdigit[]:
flag = True
break
if flag:
print["Yes, the string contains a number."]
else:
print["No, the string does not contain a number."]
0 function, as well as how to abstract this logic with a lambda function call using str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
5 and str1 = "918"
print["String is whole numeric?", str1.isnumeric[]]
str2 = "The meaning of the universe is 42"
print["String is whole numeric?", str2.isnumeric[]]
7. Then, we explored Regular Expressions and benchmarked the approaches with varying input.