Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string in python with variable formatting

How can I use variables to format my variables?

cart = {"pinapple": 1, "towel": 4, "lube": 1}
column_width = max(len(item) for item in items)
for item, qty in cart.items():
    print "{:column_width}: {}".format(item, qty)

> ValueError: Invalid conversion specification

or

(...):
    print "{:"+str(column_width)+"}: {}".format(item, qty)

> ValueError: Single '}' encountered in format string

What I can do, though, is first construct the formatting string and then format it:

(...):
    formatter = "{:"+str(column_width)+"}: {}"
    print formatter.format(item, qty)

> lube    : 1
> towel   : 4
> pinapple: 1

Looks clumsy, however. Isn't there a better way to handle this kind of situation?

like image 955
Manuel Ebert Avatar asked May 08 '12 12:05

Manuel Ebert


People also ask

How do I format a string variable in Python?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

How do you use %d and %s in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

Can we use format in variable Python?

format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

What is %d and %i in Python?

Here's what python.org has to say about %i: Signed integer decimal. And %d: Signed integer decimal. %d stands for decimal and %i for integer. but both are same, you can use both.


1 Answers

Okay, problem solved already, here's the answer for future reference: variables can be nested, so this works perfectly fine:

for item, qty in cart.items():
    print "{0:{1}} - {2}".format(item, column_width, qty)
like image 106
Manuel Ebert Avatar answered Oct 27 '22 19:10

Manuel Ebert