95

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

2 Answers 2

140

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.

3
  • 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". Apr 20, 2010 at 3:49
  • what do you do if you want to have more than 2 hex digits
    – Hippolippo
    Feb 8, 2018 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. Aug 6, 2022 at 0:15
-9

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

3
  • 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. Apr 20, 2010 at 3:48
  • @Mike, @Jake: It's for BOTH. '\xaa' is a str object. u'\xaa' is a unicode object. print repr(unichr(170)) produces u'\xaa' Apr 20, 2010 at 3: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. Apr 20, 2010 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.