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

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

    def num(s):
        """num(s)
        num(3),num(3.7)-->3
        num('3')-->3, num('3.7')-->3.7
        num('3,700')-->ValueError
        num('3a'),num('a3'),-->ValueError
        num('3e4') --> 30000.0
        """
        try:
            return int(s)
        except ValueError:
            try:
                return float(s)
            except ValueError:
                raise ValueError('argument is not a string of number')
    

提交回复
热议问题