Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 452
Alex Avatar asked Sep 12 '12 06:09

Alex


People also ask

How do you use %d and %f in Python?

The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point. The %f formatter is used to input float values, or numbers with values after the decimal place.

What does %d and %s do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

What is %s in print Python?

%s acts as a placeholder for the real value. You place the real value after the % operator. This method is often referred to as the "older" way because Python 3 introduced str. format() and formatted string literals (f-strings).


2 Answers

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.

like image 71
BrenBarn Avatar answered Oct 07 '22 09:10

BrenBarn


.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

like image 37
John La Rooy Avatar answered Oct 07 '22 11:10

John La Rooy