Python Using Databases in Python Our Diary App Switching It Up

Sahar Nasiri
Sahar Nasiri
7,454 Points

Quotation Problem

I wrote:

print('Enter 'q' to quit.')

When I get a syntax error I corrected it to:

print(r'Enter 'q' to quit.')

Yet I get the same error. Why? I thought that this "r" will solve quotation problem in a string. I have written the code below to solve the problem:

print("Enter 'q' to quit.")

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 59,892 Points

The r says it is a "raw string literal". It says to not interpret the backslash and the characters after the backslash as an escaped character and leave both intact in the string.

$ Python
Python 3.3.0 (default, Nov 26 2015, 16:04:52) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on unknown
Type "help", "copyright", "credits" or "license" for more information.
>>> len(r'\'')
2
>>> len('\'')
1

To escape quotes of the same style as the string quotes use a backslash:

print('Enter \'q\' to quit.')

Sahar Nasiri
Sahar Nasiri
7,454 Points

Thanks ;). It helped.

Why do I get this? Why does it have two backslashes?

>>> r'\''
"\\'"
Chris Freeman
Chris Freeman
Treehouse Moderator 59,892 Points

The interpreter wraps a string for output in quotes. It seems to prefer double-quotes regardless of how the string was defined. It will also choose to use single-quotes if it would make the output clearer:

>>> r'\''
"\\'"
>>> r"\""
'\\"'