0

when learning the unicode from python document, I am trying to reproduce the following example

>>> ur'Hello\u0020World !'
  u'Hello World !'
>>> ur'Hello\\u0020World !'
u'Hello\\\\u0020World !'

I use PyCharm as editor, the Python version is 2.7, However, what I get is

>>>ur'Hello\u0020World !'
Hello World !
>>>ur'Hello\\u0020World !'
Hello\\u0020World !

I don't know why the second one is different with what Python document said. What caused the difference?

user785099
  • 5,323
  • 10
  • 44
  • 62
  • possible duplicate of [What exactly do "u" and "r" string flags do in Python, and what are raw string literals?](http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l) – rafaelc May 03 '15 at 18:29
  • Are you printing your output? Generally speaking, escaped character has different `str` and `repr`. Python interpreter user `repr` in your case, but when you print it, string representation is used. – Łukasz Rogalski May 03 '15 at 18:30

1 Answers1

0

Notice in the first case the printed result is quoted like "u'hello....'" This indicates it is printing a Python string literal. The "r" prefix allows you to put backslash in a string without escaping it. Since the result is "u" alone, each backslash must be escaped.

In the second case, the output isn't quoted - so it is the string itself, and not a string literal as it would appear in Python source code. This shows exactly what the string is, and not the string as it must be encoded to be in Python source code.

joeking
  • 2,006
  • 18
  • 29