Python Check If String is Number
Last Updated :
24 Sep, 2024
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
# 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
# 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
# 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.
Python
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.
Python
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.
Python
# 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.
Python
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)
Similar Reads
Python - Check if String contains any Number
We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read
Insert a number in string - Python
We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Check if String is Empty or Not - Python
We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example: Using Comparison Operator(==)The s
2 min read
Python | Extract Numbers from String
Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let's discuss certain ways in which this problem can be solved in Python. Example Use a
5 min read
Python - Extract numbers from list of strings
We are given a list of string we need to extract numbers from the list of string. For example we are given a list of strings s = ['apple 123', 'banana 456', 'cherry 789'] we need to extract numbers from the string in list so that output becomes [123, 456, 789]. Using Regular ExpressionsThis method u
2 min read
Python - Check if string repeats itself
Checking if a string repeats itself means determining whether the string consists of multiple repetitions of a smaller substring. Using slicing and multiplicationWe can check if the string is a repetition of a substring by slicing and reconstructing the string using multiplication. [GFGTABS] Python
3 min read
Python - Check for spaces in string
Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem. Using 'in' operator'in' operator is on
3 min read
Frequency of Numbers in String - Python
We are given a string and we have to determine how many numeric characters (digits) are present in the given string. For example: "Hello123World456" has 6 numeric characters (1, 2, 3, 4, 5, 6). Using re.findall() re.findall() function from the re module is a powerful tool that can be used to match s
3 min read
Check for ASCII String - Python
To check if a string contains only ASCII characters, we ensure all characters fall within the ASCII range (0 to 127). This involves comparing each character's value to ensure it meets the criteria. Using str.isascii()The simplest way to do this in Python is by using the built-in str.isascii() method
2 min read
Python | Test if number is valid Excel column
Sometimes, while working with Python strings, we can have a problem in which we need to test for string if it's a valid Excel column. This has application in many domains including day-day programming, web development, and Data Science. Let us discuss certain ways in which this task can be performed
3 min read