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

后端 未结 29 2752
醉话见心
醉话见心 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:45

    Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.

    If your strings are in a list, you could use the map function as well.

    >>> x = ["545.0", "545.6", "999.2"]
    >>> map(float, x)
    [545.0, 545.60000000000002, 999.20000000000005]
    >>>
    

    It is only good if they're all the same type.

提交回复
热议问题