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 187 views
3 answers 192 views
2 answers 209 views
3 answers 286 views
1 answer 153 views
1 answer 167 views
...