How to Check If a String is Number in Python
To check if a string is a number in Python, you can use the isnumeric() or isdecimal() function.
The following examples show how to check if a string is a number in Python.
Using isnumeric() Function
We can use the isnumeric() function to check if a string is a number.
Suppose we have the following string:
# Declare string
string_num = "12345"
# Check if the string is a number
if string_num.isnumeric():
print("The string is a number.")
else:
print("The string is not a number.")
Output: 👇️
The string is a number.
In this example, we use the isnumeric() function to check if the string string_num is a number.
Using isdecimal() Function
We can use the isdecimal() function to check if a string is a number.
Suppose we have the following string:
# Declare string
string_num = "12345"
# Check if the string is a number
if string_num.isdecimal():
print("The string is a number.")
else:
print("The string is not a number.")
Output: 👇️
The string is a number.
In this example, we use the isdecimal() function to check if the string string_num is a number.
Conclusion
We can use the isnumeric() and isdecimal() functions to check if a string is a number in Python.