Chapter 4: Sequence types

Escaping strings

face Josiah Wang

If you need a quote inside your string, e.g. the boy's mother, how would you do this in Python?

>>> 'the boy's mother'
  File "<stdin>", line 1
    'the boy's mother'
             ^
SyntaxError: invalid syntax
>>> 

One way is to escape such quotes with a backslash (\) like in C++.

>>> 'the boy\'s mother'
"the boy's mother"

You can also enclose your string with a different type of quote (recommended for better readability).

>>> "the boy's mother"
"the boy's mother"
>>> '''the boy's mother'''
'''the boy's mother'''
>>> 'he said, "hello"'
'he said, "hello"'