Python Check If String is Number
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
Input: 95 Output: Digit Input: a Output: not a digit
Check If a String is a Number Python
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.
- Using isdigit() method
- Using Regular Expressions (re.match)
- Using isnumeric() method
- Using Python Regex
- Without any built-in methods
- Using the “try” and “float” functions
- Using “try” and “expect” block
- Using a Custom Function
- Using ASCII Values
Ways to Check if a String is an Integer in Python
Here is an Example of How to Check if the string is a number in Python.
Example : In this example the below code defines a function `check` that attempts to convert the input string to a float. If successful, it prints “Digit”; otherwise, it catches a ValueError and prints “Not a Digit.” The function is then called with the argument “95,” resulting in the output “Digit.”
Python3
def check(string): try : float (string) print ( "Digit" ) except ValueError: print ( "Not a Digit" ) check( "95" ) |
Output:
Digit
Time Complexity: O(N)
Space Complexity: O(1)
Check If String is Number in Python Using isdigit() Method
The isdigit() method is a built-in method in Python that returns True only if all characters in the string are digits else returns false if any alphabet or any special character exists in the string.
Example : 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.
Python3
# 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
Time Complexity: O(N)
Space Complexity: O(1)
Check If a String is a Number Python using Regular Expressions (re.match)
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.
Python3
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 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.
Python3
# 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)
Python Check if Given String is Numeric or Not using Python Regex
To check if a given string is numeric or not using Python regex (regular expressions), we can utilize the re.search() method. re.search() method either returns None (if the pattern doesn’t match) or a re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Example : In this example the below provided Python script uses the “re” module to define a regular expression for identifying digits. The function “check” takes a string as input and prints “Digit” if it contains only digits, otherwise prints “Not a Digit.” The script then demonstrates this functionality on various strings.
Python3
# import re module re module provides support import re # Make a regular expression for identifying a digit regex = '^[0-9]+$' # Define a function for identifying a Digit def check(string): # pass the regular expression # and the string in search() method if (re.search(regex, string)): print ( "Digit" ) else : print ( "Not a Digit" ) # Driver Code if __name__ = = '__main__' : # Enter the string string = "28" # calling run function check(string) string = "a" check(string) string = "21ab" check(string) string = "12ab12" check(string) |
Output:
Digit
Not a Digit
Not a Digit
Not a Digit
Time complexity: O(1)
Auxiliary Space: O(1)
Python Check If String is Number Without any built-in 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.
Python3
# 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)
Python 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.
Python3
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 #This code is contributed by Edula Vinay Kumar Reddy |
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.
Python3
# 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 a String represents a Number in Python using a Custom Function
The method defines a custom function, `is_number`, which iterates through each character of a given string, checking if it is a digit. The function returns `True` if all characters are digits, indicating that the string is a number, and `False` otherwise.
Example : In this example the `is_number` function iterates through each character in the input string, returning False if any character is not a digit; otherwise, it returns True. The example checks if the string “12345” is a number using the function .
Python3
def is_number(input_str): for char in input_str: if not char.isdigit(): return False return True # Example usage: input_string = "12345" result = is_number(input_string) print (f 'Is "{input_string}" a number? {result}' ) |
Output :
Is "12345" a number? True
Time Complexity: O(N)
Space Complexity: O(1)
Python 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.
Python3
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)