How to compare Python string formatting: % with .format?

PythonServer Side ProgrammingProgramming

% can either take a variable or a tuple. So you'd have to be very explicit about what you want it to do. For example, if you try formatting such that −

Example

my_tuple = (1, 2, 3)
"My tuple: %s" % my_tuple
You'd expect it to give the output:
My tuple: (1, 2, 3)

Output

But it will throw a TypeError. To guarantee that it always prints, you'd need to provide it as a single argument tuple as follows −

"hi there %s" % (name,)   # supply the single argument as a single-item tuple

Remembering such caveats every time is not that easy and may cause bugs. .format doesn't have those issues. format is also very clean looking comparatively.

raja
Published on 08-Jan-2018 06:44:42
Advertisements