我在标准库和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