0

我正在尝试将带有数字的字符串更改为小数点后 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 位?

有任何想法吗?

4

2 回答 2

3

如果字符串总是有小数点:

print (mainR+'0')[:mainR.find('.')+3]
于 2013-11-01T16:14:00.980 回答
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
于 2013-11-01T16:00:06.420 回答