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

1 Like

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 \\.”)

97 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?

3 Likes

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.

25 Likes

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.

2 Likes

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.

21 Likes

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.

12 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.

5 Likes

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.

I understood this example. print(“The escape character is \”) - > The escape character is \

It works as expected but I was trying this statement: print(["\adam", “betty”]). It prints [’\adam’, ‘betty’] instead of just [’\adam’, ‘betty’]. Any reason why?

The escape character applies to special characters that normally don’t print. It tells the interpreter to treat the character following the escape as a printable character.

"So he says, \"No way!\" and she says, \"Yeah, way!\""   

will print,

So he says, "No way!" and she says, "Yeah, way!"

The escape itself does not print. Notice how the quotes are printable?

To print an escape character, we have to escape it.

"\\ is the escape character"

will print,

\ is the escape character
7 Likes

I would also like to learn python on jupyter notebook. However on Codecademy Python three:

print (“escape\rbeez”)
escape
beez

in Jupyter nodebook Python 3
print(“escape\rbeez”)
beezpe

I understand this is a little out of scope here, but these should be the same on the platforms running the same version of the same language, right?

I have been facing strong confusion while reading the comments, so here’s a simple code explanation for you guys:
#to show single quote

print("‘Single Quote’")

#to show double quotes

print(’“Double Quotes”’)

#to show both qoutes

s_d=""“Single’Double” “”"

print(s_d)

#with escape i.e. /

double_quotes_with_escape = ““Double Quote””

print(double_quotes_with_escape)

single_quote_with_escape = ‘‘Single Quote’’

print(single_quote_with_escape)

2 Likes

Well, it looks like I am the only one who came across this. Turns out in jupyter it was adding a newline and rewriting the same line. I don’t know why it is doing that, but at least I know what it is doing. Should have figured that out earlier.

I’d just like to add that when I copied and pasted your code, it came up with an error and I had to retype the quotes myself. It could be because I’m on a Mac?

Your quotes: “ ”

My quotes: " "

Just in case anyone else gets the same problem and can’t work it out!

3 Likes

Yes, the first pair of quotation marks are smart quotes and they’re often used in anything with text (they get converted when posted on a reply here, I guess). When coding, you need to use the straight quotes (typing quotes from your keyboard to a code editor won’t convert them to smart quotes, they’ll remain straight).

1 Like

How can we command a code line to print to the next line when when the coding intergers only, on like in string = print("\n name")??

pls am new and just a beginner

Welcome to the forums! In future posts, please don’t create a separate reply, be patient and someone should respond in due time.

Here are a few methods you could use (by no means an exhaustive list):

my_int = 2 # concatenation print("\n" + str(my_int)) # .format() print("\n{0}".format(my_int)) # f-strings print(f"\n{my_int}")
1 Like

print (‘He said, “Hello”, and I was fine.’)

Output:
He said, “Hello”, and I was fine

single quotes outside mean you can use double quotes inside- there are also ways to use single quotes within single quotes.