In context of Python Raw string

Grijesh Chauhan picture Grijesh Chauhan · Dec 2, 2012 · Viewed 11.6k times · Source

My Python version is:

~$ python --version  
Python 2.6.6

I tried following in Python (I wants to show all):

1: \ use as escape sequence

>>> str('Let\'s Python')       
"Let's Python"

2: \ use as escape sequence

>>> 'Let\'s Python'             
"Let's Python"

3: str() and print as value not type

>>> print 'Let\'s Python'       
Let's Python

4: its Python a raw string

>>> repr('Let\'s Python')      
'"Let\'s Python"'

[QUESTION]

5: Python raw string

>>> print r'Let\'s Python'    
Let\'s Python

6: This, I do not understand followings:

>>> r'Let\'s Python'            
"Let\\'s Python"

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

Why \\ ? Why output in 5 and 6 are different?
r and repr() are same not same?
Also please explain about internal representation of string and raw strings are same or different.

Answer

Martijn Pieters picture Martijn Pieters · Dec 2, 2012

You are confusing raw string literals r'' with string representations. There is a big difference. repr() and r'' are not the same thing.

r'' raw string literals produce a string just like a normal string literal does, with the exception to how it handles escape codes. The produced result is still a python string. You can produce the same strings using either a raw string literal or a normal string literal:

>>> r'String with \n escape ignored'
'String with \\n escape ignored'
>>> 'String with \\n escape ignored'
'String with \\n escape ignored'

When not using a r'' raw string literal I had to double the slash to escape it, otherwise it would be interpreted as the newline character. I didn't have to escape it when using the r'' syntax because it does not interpret escape codes such as \n at all. The output, the resulting python string value, is exactly the same:

>>> r'String with \n escape ignored' == 'String with \\n escape ignored'
True

The interpreter is using repr() to echo those values back to us; the representation of the python value is produced:

>>> print 'String'
String
>>> print repr('String')
'String'
>>> 'String'
'String'
>>> repr('String')
"'String'"

Notice how the repr() result includes the quotes. When we echo just the repr() of a string, the result is itself a string, so it has two sets of quotes. The other " quotes mark the start and end of the result of repr(), and contained within that is the string representation of the python string String.

So r'' is a syntax to produce python strings, repr() is a method to produce strings that represent a python value. repr() also works on other python values:

>>> print repr(1)
1
>>> repr(1)
'1'

The 1 integer is represented as a string '1' (the character 1 in a string).