How to check if a string contains a number with Python?

Sometimes, we want to check if a string contains a number with Python.

In this article, we’ll look at how to check if a string contains a number with Python.

How to check if a string contains a number with Python?

To check if a string contains a number with Python, we can use the re.search method.

For instance, we write

import re
def has_numbers(input_string):
    return bool(re.search(r'd', input_string))

x = has_numbers("I own 1 dog")

to create the has_numbers function.

In it, we call re.search with a regex string that matches digits in the input_string to see if input_string has any digits inside.

The we call has_numbers with a string.

And since it has a number inside, x is True.

Conclusion

To check if a string contains a number with Python, we can use the re.search method.