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

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

    for number and char together :

    string_for_int = "498 results should get"
    string_for_float = "498.45645765 results should get"
    

    first import re:

     import re
    
     #for get integer part:
     print(int(re.search(r'\d+', string_for_int).group())) #498
    
     #for get float part:
     print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765
    

    for easy model :

    value1 = "10"
    value2 = "10.2"
    print(int(value1)) #10
    print(float(value2)) #10.2
    

提交回复
热议问题