Greg Castaldi
Greg Castaldi

Reputation: 365

How can I format a number for multiple prints in python3.x?

I want to be able to format a number a certain way and have it turn out this way for each print function I call rather than reformat it within each print function. I just see it as a way to clean up for code a little. Here's an example:

Given the variable:

weight = mass * conversion_const

and say it comes out to over 2 decimal places.

Then I want to print:

print('The mass of the load is %s Newtons, which is too heavy' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is too light' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is just right' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is wayy to heavy' %(format(weight, ',.2f')))

This is just for an example, it would be in a if statement if I were to create something that needed these responses, but as you can see, either way I would have to format the same variable each time. How can I avoid this?

Upvotes: 0

Views: 101

Answers (3)

Dror Hilman
Dror Hilman

Reputation: 7457

weight = "%.2f"%(mass * conversion_const)

print('The mass of the load is %s Newtons, which is too heavy'%(weight))
print('The mass of the load is %s Newtons, which is too light'%(weight))
print('The mass of the load is %s Newtons, which is just right'%(weight))
print('The mass of the load is %s Newtons, which is way to heavy'%(weight))

or even better:

weight = "The mass of the load is %.2f Newtons, which is "%(mass * conversion_const)

print(weight + 'too heavy')
print(weight + 'too light')
print(weight + 'just right')
print(weight + 'way too heavy')

Upvotes: 0

bereal
bereal

Reputation: 34282

There are quite a few options of how to extract the common formatting code, just for example:

ANSWER_FORMAT = 'The mass of the load is {0:,2f} Newtons, which is {1}'
format_answer = ANSWER_FORMAT.format

print(format_answer(right_weight, 'just_right'))
print(format_answer(heavy_weight, 'too heavy'))

(Notice, how the new formatting style can make life easier.)

Upvotes: 1

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

Format it once, store the formatted string in a variable, then use that variable.

Upvotes: 0

Related Questions