I would like to check if my value is a float with a point or a comma but isdigit() return false with a point. I would like to know why and how go through it.
> value = "0.0"
> print value.isdigit():
>>> False
My code is :
if "." in value and value.isdigit()
print "ok"
str.isdigit()
will only return true if all characters in the string are digits. .
is punctuation, not a digit.
From the Python 3 str.isdigit()
documentation:
Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal
(For Python 2, for str
objects only the ASCII digits (0
through to 9
) are considered, but for unicode
objects the same definition applies).
See the official Numeric Property definitions specification; there are 708 Unicode codepoints that match that description.
Simplifying this to general unicode categories, numeric types in Unicode have a category starting with N
, but .
does not:
>>> import unicodedata
>>> unicodedata.category(u'.')
'Po'
P
stands for punctuation here, o
for other.
Vice-versa, strings that contain only digits are not always convertable to a float or number either:
>>> unicodedata.name(u'\u2080')
'SUBSCRIPT ZERO'
>>> unicodedata.category(u'\u2080')
'No'
>>> unicodedata.digit(u'\u2080')
0
>>> u'\u2080'.isdigit()
True
>>> float(u'\u2080')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'decimal' codec can't encode character u'\u2080' in position 0: invalid decimal Unicode string
So a subscript-zero is not really 0 as far as float()
is concerned, but it is a digit.
If you want to test if a string is a valid floating point number, use float
and catch the ValueError
:
def is_float(string):
try:
float(string)
return True
except ValueError:
return False