Ryflex
Ryflex

Reputation: 5769

Force a string number to be 2 decimal places

I'm trying to change a string with a number to be 2 decimal places?

Code that cannot be edited

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

Outputs:

Student: PSO250.00

Sometimes outputs:

Student: PSO250.000

Example print outputs:

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

Correct Outputs:

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

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177640

If the string always has a decimal point:

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

Upvotes: 3

falsetru
falsetru

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

Related Questions