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

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

    The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:

       >>> import string
       >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
       ...                      int(x) or x.isalnum() and x or \
       ...                      len(set(string.punctuation).intersection(x)) == 1 and \
       ...                      x.count('.') == 1 and float(x) or x
       >>> parseStr('123')
       123
       >>> parseStr('123.3')
       123.3
       >>> parseStr('3HC1')
       '3HC1'
       >>> parseStr('12.e5')
       1200000.0
       >>> parseStr('12$5')
       '12$5'
       >>> parseStr('12.2.2')
       '12.2.2'
    

提交回复
热议问题