2

I use python 3.4 and I can format strings in two ways:

print("%d %d" %(1, 2))

and

print("{:d} {:d}".format(1, 2))

In documentation they show examples only using 'format'. Do it mean that using '%' is not good, or it does not matter which version to use?

user3654650
  • 5,283
  • 10
  • 27
  • 28

2 Answers2

8

Quoting from the official documentation,

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

So, format is the recommended way to do, going forward.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • that said % formatting has no plans of going obsolete... and I prefer it most of the time(not that my personal preference justifies its use for anyone other than myself) ... – Joran Beasley May 23 '14 at 00:20
3

In addition to the recommendations on the official site the format() method is more flexible, powerful and readable than operator '%'.

For example:

>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
>>> "Units destroyed: {players[0]}".format(players = [1, 2, 3])
'Units destroyed: 1'

and more, and more, and more... Hard to do something similar with the operator '%'.

MindHatter
  • 51
  • 2