How to parse an int or float number in a string to int or to float in Python

1 Answer

0 votes
def to_num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

print(to_num("100"))
print(to_num("3.14"))

'''
run:

100
3.14

'''

 



answered Mar 30, 2017 by avibootz

Related questions

1 answer 194 views
3 answers 200 views
2 answers 219 views
3 answers 297 views
1 answer 160 views
1 answer 177 views
...