我查看了标准库和 StackOverflow,但没有找到类似的问题。那么,有没有办法在不滚动我自己的功能的情况下执行以下操作?如果有人在没有内置方法的情况下编写了一个漂亮的函数,则可以加分。
def stringPercentToFloat(stringPercent)
# ???
return floatPercent
p1 = "99%"
p2 = "99.5%"
print stringPercentToFloat(p1)
print stringPercentToFloat(p2)
>>>> 0.99
>>>> 0.995
最佳答案
使用 strip('%')
,如:
In [9]: "99.5%".strip('%')
Out[9]: '99.5' #convert this to float using float() and divide by 100
In [10]: def p2f(x):
....: return float(x.strip('%'))/100
....:
In [12]: p2f("99%")
Out[12]: 0.98999999999999999
In [13]: p2f("99.5%")
Out[13]: 0.995
关于python - 将字符串百分比转换为 float 的干净方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12432663/