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

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

    Which, not only is ugly and slow

    I'd dispute both.

    A regex or other string parsing method would be uglier and slower.

    I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

    The issue is that any numeric conversion function has two kinds of results

    • A number, if the number is valid
    • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

    C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

    I think your code for doing this is perfect.

提交回复
热议问题