Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 68,441 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 68,441 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"\""
'\\"'