Escape Sequences in Python

Escape Sequences in Python

This is the list of all the escape sequences Python supports. You may not use many of these, but memorize their format and what they do anyway. Also try them out in some strings to see if you can make them work.

\\ Backslash (\)
\' Single- quote (')
\" Double- quote (")
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\f ASCII formfeed (FF)
\n ASCII linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII carriage return (CR)
\t ASCII horizontal tab (TAB)
\uxxxx Character with 16- bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32- bit hex value xxxxxxxx (Unicode only)
\v ASCII vertical tab (VT)
\ooo Character with octal value oo
\xhh Character with hex value hh

Here’s a tiny piece of fun code to try out:

while True:
 for i in ["/","- ","|","\\","|"]:
 print "%s\r" % i,

Study Drills

1. Memorize all the escape sequences by putting them on fl ash cards.

2. Use ”’ (triple- single- quote) instead. Can you see why you might use that instead of “””?

3. Combine escape sequences and format strings to create a more complex format.

4. Remember the %r format? Combine %r with double- quote and single- quote escapes and print them out. Compare %r with %s. Notice how %r prints it the way you’d write it in your file, but %s prints it the way you’d like to see it?

I still haven’t completely figured out the last exercise. Should I continue?

Yes, keep going, and instead of stopping, take notes listing things you don’t understand for each exercise. Periodically go through your notes and see if you can figure these things out after you’ve completed more exercises. Sometimes, though, you may need to go back a few exercises and go through them again.

What makes \\ special compared to the other ones?

It’s simply the way you would write out one backslash (\) character. Think about why you would need this.

When I use a %r format none of the escape sequences work.

That’s because %r is printing out the raw representation of what you typed, which is going to include the original escape sequences. Use %s instead. Always remember this: %r is for debugging; %s is for displaying.