Dryden Long
Dryden Long

Reputation: 10180

What is this code: %(var)s ? Python maybe?

There is an option on the backend of a website that I use that allows me to customize the data sent in a CSV file when an order has been placed for a product. There are two columns, the left column is where you assign the header and the right column is where you input the variable. The syntax for the existing variables is similar to %(order.random_variable)s or %(item.random_variable)s This looks similar to the string placeholder %s in Python and I'm fairly confident that it is related, if not the same, but I don't quite understand the syntax. Could someone please elaborate on the purpose of this code?

Oh, and for the record, I don't plan on going in and changing variables around right away. Just looking for a good jumping off point for my research into this.

Upvotes: 2

Views: 1903

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213351

That is similar to %s. The part inside the parenthesis is optional.

The only difference is that, for the first one, your values must be a tuple with exactly the number of items specified by the format string, and for the 2nd one, it must be a single mapping object (for example, a dictionary)

It's clearly listed in String formatting documentation: -

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The '%' character, which marks the start of the specifier.
  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
    .. and there are some more

Also: -

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping

An example from the docs: -

>>> print '%(language)s has %(number)03d quote types.' % \
...       {"language": "Python", "number": 2}
Python has 002 quote types.

So, the text inside the () after % and before s is a key in the dictionary.

Upvotes: 6

John Fink
John Fink

Reputation: 313

Yes, this is similar to %s. The part inside the () is referencing a key of a python dict. For example:

mydict = {'yay':'boo'}
print '%(yay)s'%mydict

# boo

Upvotes: 4

Related Questions