96

What is difference between 'aa' and '\xaa'? What does the \x part mean? And which chapter of the Python documentation covers this topic?

poke
  • 369,085
  • 72
  • 557
  • 602
Haiyuan Zhang
  • 40,802
  • 41
  • 107
  • 134

2 Answers2

142

The leading \x escape sequence means the next two characters are interpreted as hex digits for the character code, so \xaa equals chr(0xaa), i.e., chr(16 * 10 + 10) -- a small raised lowercase 'a' character.

Escape sequences are documented in a short table here in the Python docs.

mlissner
  • 17,359
  • 18
  • 106
  • 169
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    chr(170) can be interpreted without reference to a particular encoding only in the context of Python 3.X, and it's actually a "feminine ordinal indicator" ... a peculiarity of Spanish orthography, along with its sibling U+00BA "masculine ordinal indicator". – John Machin Apr 20 '10 at 03:49
  • what do you do if you want to have more than 2 hex digits – Hippolippo Feb 08 '18 at 22:13
  • @Hippolippo `\u` is the same but for up to 4 hex digits, and `\U` is the same but for up to 8 hex digits. More than this will not be needed, because of how Unicode is designed. – Karl Knechtel Aug 06 '22 at 00:15
-10

That's unicode character escaping. See "Unicode Constructors" on PEP 100

Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • 2
    No it isn't. It's for defining a specific byte in a `str`, not for making a unicode code point, which is done with the `u'\u...` notation. – Mike Graham Apr 20 '10 at 03:48
  • 1
    @Mike, @Jake: It's for BOTH. '\xaa' is a str object. u'\xaa' is a unicode object. `print repr(unichr(170))` produces `u'\xaa'` – John Machin Apr 20 '10 at 03:54
  • Oops. I seem not to have noticed the IronPython tag. *blush*. The concepts in my comment are still pretty pertinent—`\x` and `\u` remain somewhat different things. – Mike Graham Apr 20 '10 at 13:08