Note: despite the linked duplicate not being a duplicate (it explicitly asks about casting to int and float separately) I still mark it as duplicate because it contains wonderful information about the subject (and an answer similar to my solution)
Summary: I am looking for a pythonic way to convert a string into a number (an integer or a float).
I currently use a waterfall function but while it works, it is not particularly aesthetically pleasant:
def convert_to_int_or_float(a):
# maybe an integer
try:
return int(a)
except ValueError:
# nope - so can be a float or a str
try:
return float(a)
except ValueError:
# must be a str
return a
for s in ["0", "12", "-13", "14.7", "-14.7", "hello"]:
print(s, type(convert_to_int_or_float(s)))
# outputs
# 0 <class 'int'>
# 12 <class 'int'>
# -13 <class 'int'>
# 14.7 <class 'float'>
# -14.7 <class 'float'>
# hello <class 'str'>
Is there a better way to do that? (ideally though a module)
I had look at math
but did not find anything there.