Check if a String Contains a Number in Python

By James L.

Sometimes you need a string to contain only text, without any numbers.

In this guide, we will explore the following methods, to check if the string contains any numerical value:

  • Using any() function and isdigit() method
  • Using for loop
  • Using regular expressions

# Using any() function and isdigit() method

To check if a string contains any numerical digits in Python, you can use the any() function in combination with the isdigit() method.

Here is an example:

def has_number(input_string):
    # Check if a string contains any number

    return any(char.isdigit() for char in input_string)


print(has_number("I have 4 dogs"))  # True
print(has_number("I love apple"))   # False

In this example, the has_number() function takes an input string and uses a generator expression within the any() function. It iterates through each character in the input string and checks if it is a digit using the isdigit() method. The any() function returns True if at least one character in the string is a digit.

Key functions and methods

for char in str: This is a generator expression that iterates over each character (char) in the input string.

isdigit() method: This method is called on each character in the input string. It returns True if the character is a numerical digit (0-9), and False otherwise.

any() function: This function returns True if at least one element in the iterable is True. In this case, it checks if at least one character in the input string is a numerical digit.

# Using for loop

You can use a for loop to iterate through each character in a string and check if it is a number.

Here’s an example:

def has_number(input_string):
    # Check if a string contains any number using for loop
    for char in input_string:
        if char.isdigit():
            return True
    return False


print(has_number("I have 3 cats"))  # True
print(has_number("I love apple"))   # False

In this example, the isdigit() method is used to check if each character in the string is a digit (i.e. a number). The function has_number() returns True if any digit is found in the string and False otherwise.

# Using regular expression

You can use the re.search() method to check if the string contains a number using regular expressions.

Here’s an example:

import re


def has_number(input_string):
    # Define a pattern to match digits
    pattern = re.compile(r'\d')

    # Check if the pattern is present in the input string
    return bool(re.search(pattern, input_string))


print(has_number("iPhone 15 Pro"))  # True
print(has_number("I love apple"))   # False

In Python, the re module provides support for regular expressions (regex).

The re.compile() method compiles a regular expression pattern into a regex object for matching strings.

The re.search() method searches for a specified pattern within a given string and returns a Match object if there is a match; otherwise, it returns None.

  • The first argument passed to the re.search() method is a regex pattern that you want to search for within the input string. In our case, we passed \d as the regex pattern. The \d matches any digits (0-9).
  • The second argument passed to the re.search() method is the input string in which the search for the specified pattern is performed.

The bool() function is a built-in Python function that converts a value to a boolean. In this case, it is applied to the result of the re.search() method. If a match is found (Match object is not None), it returns True; otherwise, it returns False.

# Check if a string contains only numbers

You can use the isdigit() method to check if a string contains only numbers.

Here’s an example:

def has_only_numbers(input_string):

    # Check if the string contains only digits
    return input_string.isdigit()


print(has_only_numbers("iPhone 15 Pro"))  # False
print(has_only_numbers("45"))             # True
print(has_only_numbers("-33"))            # False
print(has_only_numbers("3.14"))           # False

In this example, the isdigit() method returns True if all characters in the string are digits (0-9), and False otherwise. The function has_only_numbers()uses this method to check if the entire string contains only numbers.

However, the isdigit() method cannot correctly handle negative and floating point numbers because the negative sign and decimal point are not considered a digit.

If you want to learn more, I have written a comprehensive guide on checking if a string is a number in Python. You can check it here

Conclusion:

In conclusion, we explored three different approaches to determine whether a string contains a number in Python:

For quick checks, the any() function and isdigit() method offers a concise and readable solution.

The for loop method allows iterating through each character, providing fine-grained control and flexibility. This is ideal when you need additional processing or custom checks within the loop.

Lastly, the regular expression method enables defining precise patterns for identifying specific number formats.

Ultimately, the best method depends on your specific needs and coding preferences. 

I hope this blog post was helpful!!!

Happy Coding→