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
In C# there are two different functions that handle parsing of scalar values:
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."