Using Special Characters in Strings

Suppose you want to put a single quote inside a string. If you write it directly, an error occurs:

 >>>​​ ​​'that'​​s​​ ​​not​​ ​​going​​ ​​to​​ ​​work​​'
  File "<stdin>", line 1
  'that's not going to work'
  ^
 SyntaxError: invalid syntax

When Python encounters the second quote—the one that is intended to be part of the string—it thinks the string is ended. Then it doesn’t know what to do with the text that comes after the second quote.

One simple way to fix this is to use double quotes around the string; we can also put single quotes around a string containing a double quote:

 >>>​​ ​​"that's better"
 "that's better"
 >>>​​ ​​'She said, "That is better."'
 'She said, "That is better."'

If you ...

Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.