Wul*_*ram 23 python string python-2.7 python-3.x
我查看了标准库和StackOverflow,但没有找到类似的问题.那么,有没有办法在不滚动自己的功能的情况下执行以下操作?如果有人在没有内置方式的情况下写出漂亮的功能,则可以获得奖励.
def stringPercentToFloat(stringPercent)
# ???
return floatPercent
p1 = "99%"
p2 = "99.5%"
print stringPercentToFloat(p1)
print stringPercentToFloat(p2)
>>>> 0.99
>>>> 0.995
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 53
使用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
Run Code Online (Sandbox Code Playgroud)
Flo*_* B. 18
只需 在解析之前将 替换% 为 :e-2float
float("99.5%".replace('%', 'e-2'))
Run Code Online (Sandbox Code Playgroud)
更安全,因为如果没有使用过,结果仍然是正确的%。
| 归档时间: |
|
| 查看次数: |
37010 次 |
| 最近记录: |