Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *