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

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

    Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:

    def parseIntOrFloat( aString ):
        return eval( aString )
    

    It works like this...

    >>> parseIntOrFloat("545.2222")
    545.22220000000004
    >>> parseIntOrFloat("545")
    545
    

    Theoretically, there's an injection vulnerability. The string could, for example be "import os; os.abort()". Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.

提交回复
热议问题