Python 3: using %s and .format()

25,860

Python 3.2 documentation said that, % will eventually go away.

http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

But as @regilero says, the sentence is gone from 3.3, which might suggest it's not actually the case. There are some conversations here that suggest the same thing.

As of Python 3.4 the paragraph 7.1.1 reads:

The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.

See also Python 3.4 4.7.2 printf-style String Formatting.

Share:
25,860

Related videos on Youtube

Zaur Nasibov
Author by

Zaur Nasibov

http://znasibov.info

Updated on December 23, 2020

Comments

  • Zaur Nasibov
    Zaur Nasibov over 3 years

    I have finally switched from % to the .format() string formatting operator in my 2.x code in order to make it easier to migrate to 3.x in future. It was a bit surprising to find out that not only the %-style formatting remains in Py3, but it is widely used in the standard library code. It seems logical, because writing '(%s)' % variable is a bit shorter and maybe easier to comprehend than '({})'.format(variable). But I'm still in doubt. Is it proper (pythonic?) to use both approaches in the code? Thank you.

    • Wayne Werner
      Wayne Werner about 11 years
      % formatting is slightly faster. But if you're doing that much string formatting that it matters, you probably have other more important concerns.
  • Zaur Nasibov
    Zaur Nasibov about 11 years
    Thank you very much for replying, Vlad. Indeed, they say that in the documentation, but even the standard library of 3.x is flooded with %-like formatting :( It seems that there are not that many signs of getting rid from % at all. Anyway, sticking to .format() seems right :)
  • regilero
    regilero over 10 years
    This sentence has been removed in python 3.3 documentation, it was still there in 3.2 docs.python.org/3.2/tutorial/…
  • Jeffrey04
    Jeffrey04 over 7 years
    just out of curiosity, is the older one going to be deprecated?
  • user5359531
    user5359531 almost 7 years
    I just tested bar = "baz"; print("foo %s" % bar), and it still worked in Python 3.4.3 (along with 2.7.3 and 2.6.6)