Open In App

Python Check If String is Number

Last Updated : 24 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number.

Example: Using isdigit() Method

# Python code to check if string is numeric or not

# checking for numeric characters
string = '123ayu456'
print(string.isdigit())

string = '123456'
print(string.isdigit())

Output

False
True

Explanation: In this example the code checks if the given strings (‘123ayu456’ and ‘123456’) consist only of numeric characters using the `isdigit()` method and prints the result.

There are various methods to check if a string is a number or not in Python here we are discussing some generally used methods for check if string is a number in Python those are the following.

Check If the String is Integer in Python using isnumeric() Method

The isnumeric() function is a built-in method in Python that checks whether a given string contains only numeric characters. It returns True if all characters in the string are numeric, such as digits, and False if the string contains any non-numeric character.

Example : In this example the first string ‘123ayu456’ is not numeric as it contains non-numeric characters. The second string ‘123456’ is numeric as it consists only of numeric characters.

# Python code to check if string is numeric or not
    
# checking for numeric characters 
string = '123ayu456'
print(string.isnumeric()) 
   
string = '123456'
print(string.isnumeric()) 

Output:

False
True

Time Complexity: O(n)
Auxiliary Space: O(1)

Check If String is Number Without any BuiltIn Methods

To check if string is a number in Python without using any built-in methods, you can apply the simple approach by iterating over each character in the string and checking if it belongs to the set of numeric characters.

Example : In this example the below Python code checks if the given string ‘012gfg345’ is numeric by iterating through its characters and determining if each character is a numeric digit. The final result is printed as “The string is not Number,” since ‘g’ is a non-numeric character in the string.

# Python code to check if string is numeric or not
    
# checking for numeric characters
numerics="0123456789"
string="012gfg345"
is_number = True
for i in string:
    if i not in numerics:
      is_number = False
      break
if is_number:
  print("The string is Number,")
else:
  print("The string is not Number,")

Output:

The string is not Number

Time Complexity: O(n)
Auxiliary Space: O(1)

Check If a String is a Number Python using RegEx

This method employs `re.match` to validate if a string is a number by ensuring it comprises only digits from start to finish. The function returns `True` for a match and `False` otherwise.

Example : In this example the below code defines a function `is_number_regex` using regular expressions to check if the input string consists of only digits. The example usage tests the function with the string “45678” and prints whether it is a number or not based on the function’s result.

import re

def is_number_regex(input_str):
    return bool(re.match(r'^\d+$', input_str))

# Example usage:
input_string = "45678"
result = is_number_regex(input_string)
print(f'Is "{input_string}" a number? {result}')

Output :

Is "45678" a number? True

Time Complexity: O(N)
Space Complexity: O(1)

Check If String is Number Using the “try” and “float” Functions

This approach involves attempting to convert the string to a float type using the float() function and catching any exceptions that are thrown if the conversion is not possible. If the conversion is successful, it means that the string is numeric, and the function returns True. Otherwise, it returns False.

Example : In this example the below function “is_numeric” checks if a given string can be converted to a float; it returns True if successful, False otherwise. The provided test cases demonstrate its behavior with numeric and non-numeric strings.

def is_numeric(string: str) -> bool:
    # Try to convert the string to a float
    # If the conversion is successful, return True
    try:
        float(string)
        return True
    # If a ValueError is thrown, it means the conversion was not successful
    # This happens when the string contains non-numeric characters
    except ValueError:
        return False

# Test cases
print(is_numeric("28")) # True
print(is_numeric("a")) # False
print(is_numeric("21ab")) # False
print(is_numeric("12ab12")) # False

Output:

True
False
False
False

Time complexity: O(1)
Auxiliary space: O(1)

Check If the String is Integer in Python using “try” and “expect” Block

This approach involves checking if a string is a number in Python using a “try” and “except” block, you can try to convert the string to a numeric type (e.g., int or float) using the relevant conversion functions. If the conversion is successful without raising an exception, it indicates that the string is a valid number.

Example : In this example the below code checks if a given string can be converted to an integer using the `int()` function. It prints True if successful, False if a ValueError occurs during the conversion.

# Test string 1
string = '123ayu456'

# Try to convert the string to an integer using int()
try:
    int(string)
    # If the conversion succeeds, print True
    print(True)
# If the conversion fails, a ValueError will be raised
except ValueError:
    # In this case, print False
    print(False)

# Test string 2
string = '123456'

# Repeat the process as above
try:
    int(string)
    print(True)
except ValueError:
    print(False)
# this code is contributed by Asif_Shaik

Output:

False
True

Time complexity: O(n)
Auxiliary space: O(1)

Check If String is Number using ASCII Values

The method checks if a given string is a number by examining each character’s ASCII values, ensuring that they fall within the range corresponding to digits (48 to 57). If all characters satisfy this condition, the function returns `True`; otherwise, it returns `False`.

Example : In this example the below code checks if all characters in the input string “78901” are digits (0 to 9) using ASCII values and prints whether it is a number or not.

def is_number_ascii(input_str):
    for char in input_str:
        if not 48 <= ord(char) <= 57:  # ASCII values for digits 0 to 9
            return False
    return True

# Example usage:
input_string = "78901"
result = is_number_ascii(input_string)
print(f'Is "{input_string}" a number? {result}')

Output :

Is "78901" a number? True

Time Complexity: O(N)
Space Complexity: O(1)



Practice Tags :

Similar Reads

three90RightbarBannerImg