1

我可以通过几种方式转换为十进制,例如使用正则表达式提取 int 部分并%除以100或除以第一部分。但我想知道是否有更蟒蛇的方式来做到这一点?'%'int()

4

2 回答 2

3

右剥离百分比,解析为浮点数,然后除以 100:

float(your_string.rstrip('%')) / 100.0

但是,这将允许多个%,这可能是也可能不是一件好事。如果您知道最后一个字符将始终是 a %,则可以对字符串进行切片:

float(your_string[:-1]) / 100.0
于 2013-03-28T02:23:13.330 回答
0

该数字应带有一个(且只有一个)% 符号,并位于字符串的末尾:

def perc2num(p):
    p = p.strip() # get rid of whitespace after the %
    if p.endswith('%') and p.count('%') == 1:
        return float(p[:-1])
    else:
        raise ValueError('Not a percentage.')

float()转换将去除数字和 % 之间的空格。

测试:

In [11]: perc2num('3.5%')
Out[11]: 3.5

In [12]: perc2num('-0.2')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-9a6733e653ff> in <module>()
----> 1 perc2num('-0.2')

<ipython-input-10-44f49dc456d1> in perc2num(p)
      3         return float(p[:-1])
      4     else:
----> 5         raise ValueError('Not a percentage.')

ValueError: Not a percentage.

In [13]: perc2num('-7%')
Out[13]: -7.0

In [15]: perc2num('  23%')
Out[15]: 23.0

In [16]: perc2num('  14.5 %')
Out[16]: 14.5

In [17]: perc2num('  -21.8 %  ')
Out[17]: -21.8
于 2013-03-28T06:46:27.697 回答