How can I use quotes inside of a string?

Since you need to use quotation marks in order to put in textual data, how would you go about putting in quotations marks within your printed text?

For example, if I wanted to say

Then there he stood, surveying the crop fields before saying “We have an infestation”

I tried typing it out in the print task of the learn python 3 session, but all I got was an error as the coding interpreted the second set of quotation marks like the ones used for textual data

One way to go about it is to vary your use of single quotes vs double quotes:

print(‘Then there he stood, surveying the crop fields before saying “We have an infestation”’)

As you can see, the single quotes do not conflict with the double quotes. However, I personally think it’s best practice to always use double quotes for strings, and hence your print statement would need to utilize the “escape” character: \. You simply place the backslash before any item that Python might otherwise attempt to read as a special character.

print(“Then there he stood, surveying the crop fields before saying \“We have an infestation\””)

As your experience with Python grows, you’ll find the escape character useful for “escaping” many items other than quotations, including the escape character itself:

print(“The escape character is \\.”)

7 Likes

Everything you told, works exactly as you told. Except the last one.

print(“The escape character is \.”)

and

print(“The escape character is .”)

Both give out the same output. Then what did the escape character do here?

Edit: On posting, the escape character vanished, one each from both. Is this forum working in python?

Hey vipulkataria. Great job testing it out! :slight_smile:

You’re absolutely right: in Python the outputs are identical. To elaborate further on what is actually happening:

The backslash character starts what is called an “escape sequence”. Typing \" is actually typing out an escape sequence: the result of the sequence being a single ". Typing \\ is another escape sequence whose result is a single \.

Whenever an escape sequence is read that Python doesn’t recognize, nothing happens. Python leaves the escape sequence in the code exactly as is. So this command:

print(“The escape character is \.”)

is actually telling Python to run the escape sequence \. (a backslash followed by a period), but Python doesn’t recognize these instructions, so it’s left in unchanged. Fortunately the result is the same, so a clever coder might lean on this result, but technically this is a bug in your code, and is imprecise coding. In fact, most coding languages do not leave unrecognized escape sequences in the text. Try running the following code:

print(“The escape character is \”)

and suddenly you run into an error. Python has recognized the escape sequence \" and the print statement is now left without a closing " as a result. In this instance we need to use the proposed escape sequence \\.

This was a more comprehensive explanation of the escape character, and what it is actually doing. But the inexact interpretation of the escape character “escaping” the following character’s instructions makes for a decent introduction to the concept and helps identify why you would want to escape the escape character itself.

I am sorry I am getting more confused. The escape sequence is {.} or {} ?
Ignore the curly braces please.

When I run code:
{print(“The escape character is \”)}

It gives syntax error like you said. All okay

When I run code:
{print(“The escape character is SLASH.”)}

It gives output - The escape character is SLASH.
Shouldn’t it give out the output as - The escape character is .
?

{print(“The escape character is SLASH/”)} gives the output - The escape character is SLASH/
{print(“The escape character is \r”)} gives the output - The escape character is

So the \ works for / but doesn’t work for r and .
?

{print(“The escape character is SLASH”)} strangely gives output - The escape character is \

Its like it chooses what it wants to escape and what it doesn’t want to escape? I sorry to be so dumb, this is my first language, I thought of visual basic but everyone on reddit says its waste of time, and C++ is too advanced, codeacademy picked python for me, I am still not sure whether I should have gone to web development html and css. I am a complete coding newb

Edit: And the forum post seems to remove my escape slash from all places when I post, please add to your code while testing? On second thought I replaced escape character with SLASH. Put escape character in place of SLASH while running the codes please.

The escape character starts a sequence. So when Python sees the \ it begins looking forwards to the next character to read together with the \ as a sequence. Anything you put after it will be interpreted as an escape sequence. You can try \a \r \q \b \. \! \? \~, all of these Python will read as an escape sequence, because the \ told Python to “start looking for an escape sequence”.

Not all of those are actually valid escape sequences, though. There doesn’t exist instructions for every conceivable escape sequence. When Python receives an invalid escape sequence, it leaves the backslash in. So in this instance:

print(“The escape character is \.”)

Python has read an escape sequence: \. (a backslash followed by a period), but Python doesn’t recognize this escape sequence, so it has been left in. Similarly:

print(“The escape character is \/”)

Python reads the escape sequence \/ (a backslash followed by a forward slash), which is once again an invalid escape sequence. Python leaves it in. Your following example:

print(“The escape character is \r”)

reads the escape sequence \r (a backslash followed by an r), which is a valid escape sequence. Python interprets this sequence to be a carriage return.

The way you characterized the escape sequence for the first two (as working) and the last one (as not working) is actually backwards. The first two are not working: they aren’t valid escape sequences. You’re telling Python to interpret escape sequences that have no instructions. The last one did work: Python read the escape sequence and provided a carriage return. Try this command:

print(“I like tacos.\nBut I also love burritos.”)

The backslash here starts an escape sequence: \n. This escape sequence returns a linefeed, effectively like pressing the enter or return key. But change it to:

print(“I like tacos.\zBut I also love burritos.”)

and it no longer works. You’ve given Python an invalid escape sequence. If you still see your escape sequence in the string, then Python didn’t do anything with it. This means you have a bug and should correct the escape sequence, or remove it.

By the way, by using the \ in your posts here, the forum backend is interpreting escape sequences. That’s why your \ keeps disappearing from your posts. Because, unlike Python, even invalid escape sequences are removed, which is typical behavior. These forums are providing a perfect sandbox for you to understand why you need to escape the escape character. Whenever you see \ in my post, I’m actually typing \\ in the editor.

1 Like

Additionally, when Python encounters \ in a string that contains a hard return it treats it as a continuation operator rather than raising a syntax error.

s = "Lorem ipsum dolor sit amet, consectetur adipiscing \
elit, sed do eiusmod tempor incididunt ut labore et \
dolore magna aliqua. Ut enim ad minim veniam, quis \
nostrud exercitation ullamco laboris nisi ut aliquip ex \
ea commodo consequat."

The above is a valid string. The escape character does not print.

2 Likes

Yes, great addition. :slight_smile:

Note that in this example, the \ is followed by a “newline” character, so you actually have in this instance created an escape sequence: \“newline”. “newline” is a control character, or non-printing character. They are named as such because of the “Ctrl” key on the keyboard, allowing for operations beyond just printing a character to the display.

1 Like

I hope there is a detailed write up on this escape sequence later because it is confusing. Or maybe I should search on google. Thanks for the clarification though. Quite a piece of work this escape sequence is.