How do I check if a string is a number (float)?

后端 未结 30 3840
暗喜
暗喜 2020-11-21 05:16

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         


        
30条回答
  •  -上瘾入骨i
    2020-11-21 05:52

    how about this:

    '3.14'.replace('.','',1).isdigit()
    

    which will return true only if there is one or no '.' in the string of digits.

    '3.14.5'.replace('.','',1).isdigit()
    

    will return false

    edit: just saw another comment ... adding a .replace(badstuff,'',maxnum_badstuff) for other cases can be done. if you are passing salt and not arbitrary condiments (ref:xkcd#974) this will do fine :P

提交回复
热议问题