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?
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 deprecateprintf
-style formatting.