我正在尝试将带有数字的字符串更改为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位小数?
有什么想法吗?
答案 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