98

In Python there seem to be two different ways of generating formatted output:

user = "Alex"
number = 38746
print("%s asked %d questions on stackoverflow.com" % (user, number))
print("{0} asked {1} questions on stackoverflow.com".format(user, number))

Is there one way to be preferred over the other? Are they equivalent, what is the difference? What form should be used, especially for Python3?

Whymarrh
  • 13,139
  • 14
  • 57
  • 108
Alex
  • 41,580
  • 88
  • 260
  • 469

4 Answers4

108

Use the format method, especially if you're concerned about Python 3 and the future. From the documentation:

The formatting operations described here are modelled on C's printf() syntax. They only support formatting of certain builtin types. The use of a binary operator means that care may be needed in order to format tuples and dictionaries correctly. As the new :ref:string-formatting syntax is more flexible and handles tuples and dictionaries naturally, it is recommended for new code. However, there are no current plans to deprecate printf-style formatting.

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • 18
    New documentation says this about the percent operator: "The formatting operations described here exhibit a variety of quirks that lead to a number of common errors ..." but it is **not** deprecated. http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting – guettli Sep 03 '13 at 15:14
  • 3
    It's not officially deprecated, but you're encouraged not to use it. – BrenBarn Sep 03 '13 at 16:18
  • 1
    Related: http://bugs.python.org/issue14123 – guettli Sep 11 '13 at 07:35
  • Is .format significantly slower than % ? – Qi Fan Mar 03 '16 at 22:22
  • 9
    From Python 3.6, you can [use f-strings to access previously defined variables](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498): `print(f"{user} asked {number} questions on stackoverflow.com"` – joelostblom May 26 '17 at 15:44
25

.format was introduced in Python2.6

If you need backward compatibility with earlier Python, you should use %

For Python3 and newer you should use .format for sure

.format is more powerful than %. Porting % to .format is easy but the other way round can be non trivial

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
8

The docs say that the format method is preferred for new code. There are currently no plans to remove % formatting, though.

riamse
  • 351
  • 1
  • 4
8

You can use both .No one said % formatting expression is deprecated.However,as stated before the format method call is a tad more powerful. Also note that the % expressions are bit more concise and easier to code.Try them and see what suits you best

devsaw
  • 1,007
  • 2
  • 14
  • 28
  • It's probably worth noting that `logging` module uses `%`-like syntax, so it may be preferred for consistency reasons. – sshilovsky Sep 14 '15 at 12:35