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?
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}'
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With