Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use same string format for multiple items in Python 3

As an example, I have the following numbers assigned to different variables:

a = 1.23981321; b = 34; c = 9.567123

Before I print these variables, I format them to 4 decimal places:

'{:.4f} - {:.4f} - {:.4f}'.format(a, b, c)

Which prints the following:

'1.2398 - 34.0000 - 9.5671'

Instead of assigning :.4f to each placeholder { }, is there a way to declare :.4f once to format all of the values?

like image 729
wigging Avatar asked Dec 02 '14 15:12

wigging


2 Answers

Just a little extra for people like me who just don't want to type '{:4f} {:4f} {:4f} {:4f} {:4f} {:4f} {:4f} {:4f}' or something like that for printing a whole list in a certain precision or something like that.

If you use a formatstring like suggested in the answer by Ffisegydd and you really only want to repeat a certain format, you can do the following:

fmtstr = '{:.4f}\t' * len(listOfFloats)
print(fmtstr.format(*listOfFloats))

This will print all numbers in the list in the specified format without typing the format twice! (Of course you can also simply multiply your string with any integer.)

This method has the caveat that you cannot print 8 numbers delimited by - for instance and end without this string. For that you would need a construct like this:

fmtstr = '{:.4f} - ' * 7 + '{:.4f}'
like image 33
BUFU Avatar answered Nov 14 '22 23:11

BUFU


a = 1.23981321
b = 34
c = 9.567123

print('{:.4f} - {:.4f} - {:.4f}'.format(a, b, c)) # Original

print('{a:{f}} - {b:{f}} - {c:{f}}'.format(a=a, b=b, c=c, f='.4f')) # New

It's easier to do if you use keyword arguments so you can have {a}, as opposed to positional arguments. This allows you to use the format f = '.4f' in multiple places in your format string.

If you need to keep everything short though, then you can mix positional and keyword arguments (thanks to Martijn for tip) and also put your fmt string on a separate line

fmt = '{:{f}} - {:{f}} - {:{f}}'
print(fmt.format(a, b, c, f='.4f'))
like image 198
Ffisegydd Avatar answered Nov 14 '22 21:11

Ffisegydd