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

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

    Just Mimic C#

    In C# there are two different functions that handle parsing of scalar values:

    • Float.Parse()
    • Float.TryParse()

    float.parse():

    def parse(string):
        try:
            return float(string)
        except Exception:
            throw TypeError
    

    Note: If you're wondering why I changed the exception to a TypeError, here's the documentation.

    float.try_parse():

    def try_parse(string, fail=None):
        try:
            return float(string)
        except Exception:
            return fail;
    

    Note: You don't want to return the boolean 'False' because that's still a value type. None is better because it indicates failure. Of course, if you want something different you can change the fail parameter to whatever you want.

    To extend float to include the 'parse()' and 'try_parse()' you'll need to monkeypatch the 'float' class to add these methods.

    If you want respect pre-existing functions the code should be something like:

    def monkey_patch():
        if(!hasattr(float, 'parse')):
            float.parse = parse
        if(!hasattr(float, 'try_parse')):
            float.try_parse = try_parse
    

    SideNote: I personally prefer to call it Monkey Punching because it feels like I'm abusing the language when I do this but YMMV.

    Usage:

    float.parse('giggity') // throws TypeException
    float.parse('54.3') // returns the scalar value 54.3
    float.tryParse('twank') // returns None
    float.tryParse('32.2') // returns the scalar value 32.2
    

    And the great Sage Pythonas said to the Holy See Sharpisus, "Anything you can do I can do better; I can do anything better than you."

提交回复
热议问题