强制字符串编号为2位小数

时间:2013-11-01 15:58:00

标签: python regex python-2.7

我正在尝试将带有数字的字符串更改为2位小数?

无法编辑的代码

mainR = pull1.group(0).title().replace(u"£", "PSO")
print mainR 

输出:

Student: PSO250.00

有时输出:

Student: PSO250.000

打印输出示例:

Student: PSO250.000
StudentB: PSO323.42424242
ClassTotal: PSO10.0
Class: PSO1.00000000

正确输出:

Student: PSO250.00
StudentB: PSO323.42
ClassTotal: PSO10.00
Class: PSO1.00

如何更改它以强制字符串,以便在250.000出现时,数字会被更改/强制为2位小数?

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

如果字符串始终有小数点:

print (mainR+'0')[:mainR.find('.')+3]

答案 1 :(得分:2)

使用捕获组:

>>> re.sub('(\.\d\d)\d+', r'\1', 'PSO250.000')
'PSO250.00'
>>> re.sub('(\.\d\d)\d+', r'\1', 'PSO250.00000')
'PSO250.00'

<强>更新

>>> output = '''Student: PSO250.000
... StudentB: PSO323.42424242
... ClassTotal: PSO10.0
... Class: PSO1.00000000'''

>>> print re.sub('(?<=\.)\d+', lambda m: m.group()[:2].ljust(2, '0'), output)
Student: PSO250.00
StudentB: PSO323.42
ClassTotal: PSO10.00
Class: PSO1.00