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 String is a Number in Python
Below are the lists of all the methods:
- Using isdigit() method
- Using isnumeric() method
- Using Python Regex
- Without any built-in methods
- Using the “try” and “float” functions
- Using “try” and “expect” block
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.
Python3
def check(string): try : float (string) print ( "Digit" ) except ValueError: print ( "Not a Digit" ) check( "95" ) |
Output:
Digit
Python Check if String is Number 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.
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), where N is the length of the string as we traverse through the whole string.
Space Complexity: O(1), as it requires only constant memory.
Python Check If String is Number 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.
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.
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) |
Digit Not a Digit Not a Digit Not a Digit
Time complexity: O(1) as the program runs only 4 times.
Auxiliary Space: O(1) as it only stores the input string.
Python Check If String is Number Without any built-in methods
To check if a 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.
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), where n is the length of the string.
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.
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 |
True False False False
Time complexity: O(1)
Auxiliary space: O(1)
Python Check If String is Number 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.
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 |
False True
Time complexity: O(n)
Auxiliary space: O(1)