What are the backslashes in the string?

In the practice for .format() the backslashes are not included, yet I was supposed to know that it was needed? Why was it not shown in the example code?

"The poem \"{}\" is written by {}."

The topic of escape characters must have come up in early lessons on strings.

Above, the quotes inside the string are escaped so they are ignored by the string parser and render as printed characters.

The output will look like,

The poem "I Hear America Singing" is written by Walt Whitman.

We can also write the code so the string is in single quotes. This way no excapement is required.

'The poem "{}" is written by {}.'

Is there any way in which doing the method provided in this exercise:

'The poem \"{}\" is written by {}.'.format(title, poet)

is better than:

'The poem "%s" is written by %s.' % (title, poet)

The second method seems simpler to me. Am I missing something? Is there a scenario where .format() is better?

The second example is legacy code inherited from C and written into early versions of Python, while the first was a late addition to version 2.7.x, i believe. It is far superior to the its predecessor in many ways.

This page compares the two…


Study the examples and in the end, ask yourself, which is more powerful and robust?


When the opening/closing quotes are single, we don’t need to escape double quotes in the string.

'The poem "{}" is written by {}.'.format(title, poet)