user308827
user308827

Reputation: 22041

Python format output in concise manner

Is there any conciser way to express:

'{:f};{:f};{:f};{:f};{:f}'.format(3.14, 1.14, 2.14, 5.61, 9.80)

such that one does not need to write{:f} multiple times?

Upvotes: 0

Views: 59

Answers (2)

101
101

Reputation: 8999

You could use any nice way you can think of to generate the string, for example using join:

';'.join(['{:f}' for _ in range(5)]).format(3.14, 1.14, 2.14, 5.61, 9.80)

Here's another variation with the format inside the list comprehension. This is nice because it doesn't require typing the length of the list.

nums = [3.14, 1.14, 2.14, 5.61, 9.80]
';'.join(['{:f}'.format(n) for n in nums])

Upvotes: 2

Oliver W.
Oliver W.

Reputation: 13459

Inspired by figs's answer (upvoted):

('{:f};'*5).format(3.14, 1.14, 2.14, 5.61, 9.80)[:-1] # strip the trailing semicolon

Upvotes: 4

Related Questions