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

后端 未结 30 3920
暗喜
暗喜 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条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 05:47

    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
    

提交回复
热议问题