how to escape quotes in python – escape quotes from string

In this Python tutorial, we are going to show you how to escape quotes from a string in Python. This is really a great problem ( actually an irritating problem ) when you are having a quote in your string.

The reason is that a single quote or double quote itself is a special character we use in our Python program.
In many cases, it has been seen that you want to print a string or you want to work with a string. But the problem you face when there are one or more quotes in that string.

In Python programming when you run a program it starts checking the codes. Whenever quote is found the quote is treated as a special defined character. Thus it creates a problem for us.



Let us understand the problem and its solution with some easy examples.

You may also read,

Escape quotes from a string in python

Look at the below string:

Hello, I don't like single quote at all

Now you have to print it out in Python. What will you do first if you don’t know about the problem with a single quote in a string?

The print syntax in python is:

print(' ')

Put anything in that single quotes to print. You may also use double quotes.

Escape from single quote in a string in Python

If you use the below code:

  print('hello I don't like single quote at all')

The output will be:

  print('hello I don't like single quote at all')
                    ^
  SyntaxError: invalid syntax

Because of that single quote, you will get an error like this.

don’t – here just because of this single quote we are getting an error. So we need to escape from this single quote.

Solutions:

  1. Put the string in between double quotes instead of single quotes.
  2. Put the escaping character before the single quote in the string.

You can use the first solution like this:

print("hello I don't like single quote at all")

Output:

hello I don't like single quote at all

Process finished with exit code 0

Here is the Second solution:

In Python, the backslash is an escaping character.

So you can use it like the below:

print('hello I don\'t like single quote at all')

Output:

hello I don't like single quote at all

Process finished with exit code 0

Escape from double quote in a string in Python

Now suppose you have to print the below line:

She said, “You are looking nice”. And I smiled

You can do the below:

print("She said, \"You are looking nice\". And I smiled")

Or you can also do this:

print('She said, "You are looking nice". And I smiled')

The output for both of those will be same as below:

She said, "You are looking nice". And I smiled

Process finished with exit code 0

Guess The Number Game Using Java with Source Code

Leave a Reply

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