Python – How to check if string is a number

Python – Check if string is a number

To check if a string represents a number (integer or floating-point) in Python, you can use a combination of methods like int(), and float() within a try-except block.

def is_number(string):
    try:
        # Check if the string is a valid integer
        int_value = int(string)
        return True
    except ValueError:
        try:
            # Check if the string is a valid float
            float_value = float(string)
            return True
        except ValueError:
            return False
  1. The is_number function first attempts to convert the input string to an integer using int(string). If successful, it returns True.
  2. If the first conversion fails (raises a ValueError), it then attempts to convert the string to a float using float(string). If successful, it returns True.
  3. If both conversions fail, the function returns False.

Example

Now, let us write a Python program, where we take some string values, and check if they are valid numbers.

Python Program

def is_number(string):
    try:
        # Check if the string is a valid integer
        int_value = int(string)
        return True
    except ValueError:
        try:
            # Check if the string is a valid float
            float_value = float(string)
            return True
        except ValueError:
            return False

# Example usage:
string1 = "123"
string2 = "3.14"
string3 = "Hello"

print(f'Is "{string1}" a number? {is_number(string1)}')
print(f'Is "{string2}" a number? {is_number(string2)}')
print(f'Is "{string3}" a number? {is_number(string3)}')
Run Code Copy

Output

Is "123" a number? True
Is "3.14" a number? True
Is "Hello" a number? False

Related Tutorials

Code copied to clipboard successfully 👍