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

3 Likes