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?

0

2 Answers 2

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.

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

1 Comment

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) ...
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 '%'.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.