[Tutor] Python = {0}.format

Danny Yoo dyoo at hashcollision.org
Mon Aug 18 00:46:38 CEST 2014


> print("The original quote is: {0}".format(quote))
> print("The new quote is:{0}".format(quote.replace(replaceWord,replaceWith)))

Hi Abid,


You should be able to change this to the equivalent code:

    print("The original quote is: " + quote)
    print("The new quote is:" + quote.replace(replaceWord,replaceWith))

which does not use string formatting, but just plain string
concatenation.  I believe it should have the same meaning, since we
know the things we're concatenating are strings.


Python includes a mini "templating language" for having a strings with
fill-me-ins, and letting you fill in the fill-me-ins later.  In such a
small example as the one above, I'd argue that templates are overkill.
You'll note that the non-templated version is even shorter than the
original code that uses templates.

String templating makes a lot more sense outside of a toy context,
when the output isn't a one-liner.  If you have access to a good
public library, find the classic book Jon Bentley's "Programming
Pearls" and read Chapter 3 on Data Structures Programs: it discusses a
rationale for "Form Letter Programming".


More information about the Tutor mailing list