Reputation: 5769
I'm trying to change a string with a number to be 2 decimal places?
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
How can I change it so that it forces the string so that if it comes out at 250.000
the number would be changed/forced to be 2 decimal places?
Any ideas?
Upvotes: 0
Views: 359
Reputation: 177640
If the string always has a decimal point:
print (mainR+'0')[:mainR.find('.')+3]
Upvotes: 3
Reputation: 369064
Using capturing group:
>>> re.sub('(\.\d\d)\d+', r'\1', 'PSO250.000')
'PSO250.00'
>>> re.sub('(\.\d\d)\d+', r'\1', 'PSO250.00000')
'PSO250.00'
UPDATE
>>> 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
Upvotes: 2