6

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?

1
  • If you came here and don't need the minus signs, numpy may fit. np.set_printoptions(precision=4); print(np.array(my_tuple)). Commented Dec 8, 2022 at 21:38

2 Answers 2

12
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'))
Sign up to request clarification or add additional context in comments.

3 Comments

You can also mix positional and keyword fields: '{:{f}} - {:{f}} - {:{f}}'.format(a, b, c, f='.4f').
The '{:{f}} - {:{f}} - {:{f}}'.format(a, b, c, f='.4f') approach is what I was looking for. Is there anyway to make this even shorter? It's still longer than the original approach so there really isn't much of a reason to do this for my particular example.
Probably the best thing do do would be to have s = '{:{f}} - {:{f}} - {:{f}}'; print(s.format(...)). So put your format string on a different line.
2

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}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.