将字符串百分比转换为浮点数的干净方法是什么? [英] What is a clean way to convert a string percent to a float?
本文介绍了将字符串百分比转换为浮点数的干净方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我查看了标准库和 StackOverflow,并没有发现类似的问题.那么,有没有办法在不滚动我自己的函数的情况下执行以下操作?如果有人在没有内置方式的情况下编写了漂亮的函数,则可以加分.
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way.
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
这篇关于将字符串百分比转换为浮点数的干净方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文