How can I use Python to check if a string is a number (float or int)?
I want to check if a string represents a numeric value (either an integer or a float) in Python. For example:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
The above code works but feels a bit clunky. How can I achieve this more effectively using python check if string is number?
Hey @keerti_gautam
_“Using str.replace with float()”
You can clean the string to handle edge cases like signs (+, -) and decimals before checking if it can be converted to a float.
def is_number(s):
if s.replace('.', '', 1).replace('-', '', 1).isdigit():
return True
try:
float(s)
return True
except ValueError:
return False
print(is_number("123")) # True
print(is_number("12.3")) # True
print(is_number("abc")) # False
Hey Everyone!
Hope All are doing great! Here is the Answer to the above Question:-
“Using Regular Expressions”
Regular expressions provide a more compact and precise way to validate if a string is a numeric value. This method is cleaner and ensures that you only allow valid number formats, including optional signs and decimals.
import re
def is_number(s):
return bool(re.match(r'^-?\d+(\.\d+)?
Regular expressions are great for advanced string validation, especially when you want to handle optional signs and decimals in one go., s))
print(is_number(“123”)) # True
print(is_number(“12.3”)) # True
print(is_number(“-12.3”)) # True
print(is_number(“abc”)) # False
Regular expressions are great for advanced string validation, especially when you want to handle optional signs and decimals in one go.
“Using str.isdigit for Integers or Try-Catch for Floats”
To simplify the logic, you can split the validation into separate checks for integers and floats. This method keeps it easy to understand and manage.
def is_number(s):
if s.isdigit(): # Checks for integers
return True
try:
float(s) # Floats are checked here
return True
except ValueError:
return False
print(is_number("123")) # True
print(is_number("12.3")) # True
print(is_number("abc")) # False
This approach is effective for basic cases, where you first check if the string is an integer (using isdigit
), and then handle floats using the try-except
block.
Let me know if you have further doubts on the above question.