Escape Quotes from String in Python

As you must already know, quotes are used in Python to delimiter a string. In other words, quotes are interpreted by Python as the beginning or end of a string. Nevertheless, you can face a situation where your string actually includes a quote, and it breaks your code:

print("She said that "I was mean".")
Code language: Python (python)

Output:

File "<string>", line 1 print("She said that "I was mean".") ^ SyntaxError: invalid syntax
Code language: JavaScript (javascript)

In this tutorial, we’ll see how we can handle this situation in a simple way to solve this mildly infuriating issue.

Escape from single quote

If you are using single quotes (‘) in your code, you have two options to escape them.

  • Add an escape character (\) before your additional quotes in your string. Using the example we used in the introduction, we’ll end up with :
print('She said that \'I was mean\'.')
Code language: PHP (php)

Output:

She said that 'I was mean'.
Code language: JavaScript (javascript)
  • Use double-quotes instead of single quote in your string. If you use single-quote as your delimiter and double quotes inside it, Python will understand it and print your string correctly:
print('She said that "I was mean".')
Code language: Python (python)

Output:

She said that "I was mean".
Code language: JavaScript (javascript)

The second is, in my opinion, more confusing than the first one because it’s harder to spot issues if you mix both quotes. That being said, it works and it’s completely up to you.

Escape from double quote

The logic is precisely the same as the one we saw just before, wrap your string into double quotes, BUT use a single quote to delimiter the citation inside it.

print("She said that 'I was mean'.")
Code language: PHP (php)

You can also escape double quotes using the escape character (\).

Leave a Reply

Your email address will not be published. Required fields are marked *