1

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
4
  • 1
    It's not tuple, it's a list. Commented May 21, 2014 at 15:16
  • Could you show your expected output for clarification? Commented May 21, 2014 at 15:16
  • right, got my terms a little off there Commented May 21, 2014 at 15:16
  • 6
    Don't try everything you can. Try the thing that is supposed to work, and if it doesn't, show us that code and the corresponding stack trace. Commented May 21, 2014 at 15:17

1 Answer 1

7

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

3 Comments

When I use FORMAT.format(*[x]), it gives Tuple Index out of Range
Remove the brackets form around the x
@Chrystael that's because you're trying to unpack a list with a single element (which just happens to be a list itself) to a function expecting two arguments - it's *x not *[x].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.