Ankur Agarwal
Ankur Agarwal

Reputation: 24788

Elegant way to format single string having multiple call to `format()` (format chaining)

I am trying to substitute a variable using format() and then format the resulting string using format().

This is what I ended up doing:

>>> '{:^50}'.format("Missing files for device : {0}".format(var))
'          Missing files for device : abc          '

where var is a variable holding 'abc'. Is there a better way to get the same result?

Upvotes: 3

Views: 97

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

You may join the strings and pass the joined string to format function as:

>>> center_content = ["Missing files for device :", "abc"]

>>> '{:^50}'.format(' '.join(center_content))
'          Missing files for device : abc          '

Upvotes: 1

wim
wim

Reputation: 363566

In your case, there is a simpler way:

>>> "Missing files for device : {0}".format(var).center(50)
'          Missing files for device : abc          '

Calling format twice is not necessary here.

Upvotes: 3

Related Questions