Design

Tuesday, November 2, 2010

' \ ' Escapes in Python

I have previously mentioned that '\n' codes for a new line. The backslash is known in Python as an escape.
>>> print "\tThis is a tabbed line"
This is a tabbed line
>>> print "This sentence \nis split on \nthree lines"
This sentence
is split on
three lines
>>> print "Type \\ for a backslash"
Type \ for a backslash
>>> print "Verticle \vTab"
Verticle
Tab
>>> print "Shopping List: \vPrenatal vitamins \vCocoa Butter \
... \vOrange juice"
Shopping List:
Prenatal vitamins
Cocoa Butter
Orange juice
>>> print "Shopping List: \n\t*Prenatal vitamins \
...\n\t*Cocoa Butter \n\t*Orange juice"
Shopping List:
*Prenatal vitamins
*Cocoa Butter
*Orange juice
>>> print 'Prevent the single quote 5\'5" from ending the string'
Prevent the single quote 5'5" from ending the string
>>> print "Prevent the double quote 5'5\" from ending the string"
Prevent the double quote 5'5" from ending the string

Notice that I also used a backslash in my string so that I could continue onto the next ine without Python thinking my string was done. There are other escapes in Python you can read about. "Carriage return" is a term from type writers to mean that you move to the beginning of a line. Linefeed and formfeed are also typewriter terms. \n and \t will be the most frequently used, though you may also want to be familiar with other escapes for unique problems.

No comments:

Post a Comment