Python way of printing: with 'format' or percent form?

PythonPrintingFormat

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

.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

Solution 3 - Python

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - PythonBrenBarnView Answer on Stackoverflow
Solution 2 - PythonJohn La RooyView Answer on Stackoverflow
Solution 3 - PythonriamseView Answer on Stackoverflow
Solution 4 - PythondevsawView Answer on Stackoverflow