Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 67,989 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 67,989 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"\""
'\\"'