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

后端 未结 30 3844
暗喜
暗喜 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:34

    User helper function:

    def if_ok(fn, string):
      try:
        return fn(string)
      except Exception as e:
        return None
    

    then

    if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
    is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])
    

提交回复
热议问题