Python string formatting: % vs. .format

Answer

To answer your first question... .format just seems more sophisticated in many ways. You can do stuff like re-use arguments, which you can't do with %. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"hi there %s"% name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

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

which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking

All python Questions

Ask your interview questions on python

Write Your comment or Questions if you want the answers on python from python Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---