[Tutor] string format preceeded with letter 'r'

D-Man dsh8290@rit.edu
Tue, 10 Jul 2001 12:14:40 -0400


On Tue, Jul 10, 2001 at 06:08:26PM +0200, Daniel Kinnaer wrote:

| Now here's the question:
| 
| aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
| ---------------------^
| 
| Why do we need to write an 'r' in front of sub_key? I've been doing some
| tests and it also works without this 'r' in front of the sub_key.. Now why
| is that? What is the purpose of this 'r' anyway? Can it be something else as
| well?

The r means that you have a "raw" string.  If it worked without the r
in your tests, then you were lucky, or not, because you didn't test
the certain cases where it will fail.  Try something like the
following :

>>> print r"T\tE\nS\rT"
T\tE\nS\rT
>>> print "T\tE\nS\rT"
T       E
T
>>>

The backslash '\' is used as an escape character.  Some escape
sequences have an actual meaning, and they are substituted.  If the
escape sequence is meaningless the backslash stays in the string.  In
my example, \t means tab, \n means newline and \r means carriage
return (what happened above was the S was printed, then the "carriage"
was returned to the beginning of the line and the T was printed
causing the S to no longer be seen -- think of a typewriter).  To
include a '\' in a string you either need to use raw strings, as you
have above, or escape each backslash.  ie
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"

HTH,
-D