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.
You are confusing raw string literals
r''
with string representations. There is a big difference.repr()
andr''
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: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 ther''
syntax because it does not interpret escape codes such as\n
at all. The output, the resulting python string value, is exactly the same:The interpreter is using
repr()
to echo those values back to us; the representation of the python value is produced:Notice how the
repr()
result includes the quotes. When we echo just therepr()
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 ofrepr()
, and contained within that is the string representation of the python stringString
.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:The
1
integer is represented as a string'1'
(the character1
in a string).