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

后端 未结 29 2781
醉话见心
醉话见心 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 05:08

    I use this function for that

    import ast
    
    def parse_str(s):
       try:
          return ast.literal_eval(str(s))
       except:
          return
    

    It will convert the string to its type

    value = parse_str('1')  # Returns Integer
    value = parse_str('1.5')  # Returns Float
    

提交回复
热议问题