What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
def is_numb
For int
use this:
>>> "1221323".isdigit()
True
But for float
we need some tricks ;-). Every float number has one point...
>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False
Also for negative numbers just add lstrip()
:
>>> '-12'.lstrip('-')
'12'
And now we get a universal way:
>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False