Home »
Python
How to Check if a String is a Float in Python
Last Updated : April 28, 2025
In Python, a string can often be converted into an integer or a float. However, checking if a string can be interpreted as a valid float requires specific approaches. In this chapter, we will explore multiple methods to verify if a string is a float in Python.
Checking String is Float Using try-except with float() Function
You can convert a string to a float using the float()
function inside a try-except block to check if it is a valid float.
Example
This example demonstrates using exception handling to check for float conversion.
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
# Test cases
print(is_float("123.456")) # True
print(is_float("abc")) # False
The output of the above code would be:
True
False
Checking String is Float Using str.replace() and str.isdigit()
You can remove a decimal point from the string and use isdigit()
to check if the remaining characters are all digits.
Example
This example demonstrates validating float format manually by checking for a single decimal point.
def is_float(s):
if s.count('.') == 1:
s = s.replace('.', '')
return s.isdigit()
return False
# Test cases
print(is_float("123.456")) # True
print(is_float("123.45.6")) # False
print(is_float("abc")) # False
The output of the above code would be:
True
False
False
Checking String is Float Using Regular Expressions (Regex)
You can use the re
module with a regular expression pattern to check if a string matches the float format.
Example
This example demonstrates using regular expressions to match valid float patterns in strings.
import re
def is_float(s):
pattern = r'^-?\d*(\.\d+)?$'
return bool(re.match(pattern, s))
# Test cases
print(is_float("123.456")) # True
print(is_float("-123.456")) # True
print(is_float("123.")) # False
print(is_float("abc")) # False
The output of the above code would be:
True
True
False
False
Checking String is Float Using str.isnumeric() with Additional Checks
You can combine isnumeric()
and manual decimal checks to create a simple float validator for basic cases.
Example
This example demonstrates a numeric check after removing one decimal point.
def is_float(s):
if s.replace('.', '', 1).isnumeric() and s.count('.') < 2:
return True
return False
# Test cases
print(is_float("123.456")) # True
print(is_float("123")) # True
print(is_float("12.34.56")) # False
The output of the above code would be:
True
True
False
Exercise
Select the correct option to complete each statement about checking if a string is a float in Python.
- One simple way to check if a string can be converted to a float is to use a ___ block.
- Inside the try block, you attempt to convert the string using the ___ function.
- If a string cannot be converted to a float, a ___ exception is typically raised.
Advertisement
Advertisement