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?
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".
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With