You can use isdigit() + replace() or float() + Exception handling to check if a string is a float in Python. Using the float function try to convert the string to a floating point value, and if it’s failed that it’s not a potential float value.
Python checks if the string is a float example
Simple example code.
s = "10.657"
# using isdigit() + replace()
res = s.replace('.', '', 1).isdigit()
print(res)
# using float()
try:
float(s)
res = True
except:
print("Not a float")
res = False
print(res)
Output:
Using regular expression to check if the string is a valid float
import re def is_float(string): pattern = r"^[-+]?[0-9]*\.?[0-9]+$" match = re.match(pattern, string) return bool(match) s = "10.657" print(is_float(s))
Checking to see if a string is an integer or float
If the string is convertible to an integer, it should be digits only.
if NumberString.isdigit():
Number = int(NumberString)
else:
Number = float(NumberString)
If you already have Number confirmed as a float, you can always use is_integer
(works with negatives):
if Number.is_integer():
Number = int(Number)
Do comment if you have any doubts or suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.