1

Which of these Python string interpolations is proper (not a trick question)?

  1. '%s' % my_string
  2. '%s' % (my_string)
  3. '%s' % (my_string, )

If it varies by version, please summarize.

3
  • 1
    It depends on what version of python you are using. Commented Mar 21, 2011 at 18:34
  • When you tried them, what did you learn? Please post your actual results you actually got by running the actual lines of code in an actual Python implementation. It will really help others if you could post what you saw. Commented Mar 21, 2011 at 19:27
  • @TheCommunistDuck your sense of smell if really sharp my friend. Commented Mar 19, 2012 at 20:02

2 Answers 2

3

Old format

The first one is the most common one. The third has unnecessary parenthesis and doesn't help the legibility if you've only one object you want to use in your format-string. The second is just plain silly, because that's not even a tuple.

New format

Nowadays starting with Python 2.6, there's a new and recommended way of formatting strings using the .format-method:

In your case you would use:

'{}'.format(my_string)

The advantage of the new format-syntax are that you enter more advanced formattings in the format string.

Sign up to request clarification or add additional context in comments.

1 Comment

format is in Python 2.6+
2

All three of these are equivalent.

The first two are exactly equivalent, in fact. Putting brackets around something does not make it a tuple: putting a comma after it does that. So the second one evaluates to the first.

The third is also valid: using a tuple is the normal way of doing string substitution, but as a special case Python allows a single value if there is only one element to be substituted.

1 Comment

They're equivalent so long as "my_string" actually is a string, and never a tuple.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.