How do I parse a string to a float or int?

后端 未结 29 2809
醉话见心
醉话见心 2020-11-21 04:43

In Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 545.2222? Or parse the string \"31\" t

29条回答
  •  清歌不尽
    2020-11-21 04:56

    Instead of considering eval, following methods can be used to solve the problem

    if '.' in string:
        print(float(string))
    else:
        print(int(string))
    

    try-except can also be used as an alternative. Try converting string to int inside the try block. If the string would be a float value, it will throw an error which will be catched in the except block, like this

    try:
        print(int(string))
    except:
        print(float(string))
    

提交回复
热议问题