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


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

Updated on: 19-Feb-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements