Chrystael
Chrystael

Reputation: 179

Using String Formatting in Python

I have a predetermined format

FORMAT = "{0:<30}{1}"

Which I want to use in relation to tuple x, where tuple x is something like

['bananas', '246']

I've tried everything I can, and it keeps spitting out errors. How do I use the format with my tuple?

EDIT: My expected output should (I think) simply put spaces between the first and second items, like

Bananas                                     246

I tried

x = FORMAT(x)

which gives

TypeError: 'str' object is not callable

Upvotes: 1

Views: 88

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122150

str.format expects multiple arguments corresponding to the placeholders in the string being formatted, rather than a single argument that contains multiple items to be formatted. Therefore I think what you want is:

FORMAT.format(*['bananas', '246'])

where the * means "unpack the items in the iterable as separate positional arguments", i.e. effectively calls:

FORMAT.format('bananas', '246')

If your list is e.g.

x = ['bananas', '246']

then you can convert to a formatted string like:

x = FORMAT.format(*x)

Upvotes: 7

Related Questions