python - 将字符串百分比转换为 float 的干净方法是什么?

标签 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

最佳答案

使用 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/

相关文章:

python - 引用上一行的值与map或apply

c - 在C中将2个ascii字符存储到1个整数中

c++ - syslog const char* 到字符串

python - 在 Python 中,如何从 chardet 模块开始?

Python 将纪元时间转换为星期几

python - 使用 pandas 将行转换为列

带线程的 Python 程序无法捕获 CTRL+C

Python Anaconda 错误 : NoPackagesFoundError: Packages missing in current win-64 channels:

python - 如何在 PuLP 中向线性优化模型添加条件约束

c++ - 使用 std::string 构造函数复制 const char *