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

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

    Use:

    def num(s):
        try:
            for each in s:
                yield int(each)
        except ValueError:
            yield float(each)
    a = num(["123.55","345","44"])
    print a.next()
    print a.next()
    

    This is the most Pythonic way I could come up with.

提交回复
热议问题