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

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

    The YAML parser can help you figure out what datatype your string is. Use yaml.load(), and then you can use type(result) to test for type:

    >>> import yaml
    
    >>> a = "545.2222"
    >>> result = yaml.load(a)
    >>> result
    545.22220000000004
    >>> type(result)
    
    
    >>> b = "31"
    >>> result = yaml.load(b)
    >>> result
    31
    >>> type(result)
    
    
    >>> c = "HI"
    >>> result = yaml.load(c)
    >>> result
    'HI'
    >>> type(result)
    
    

提交回复
热议问题