When does the escape character work within raw strings?

Rhodri James rhodri at wildebst.demon.co.uk
Fri May 22 14:22:49 EDT 2009


On Fri, 22 May 2009 15:47:49 +0100, walterbyrd <walterbyrd at iname.com>  
wrote:

> On May 21, 9:44 pm, "Rhodri James" <rho... at wildebst.demon.co.uk>
> wrote:
>
>> Escaping the delimiting quote is the *one* time backslashes have a
>> special meaning in raw string literals.
>
> If that were true, then wouldn't r'\b' be treated as two characters?

It is.

>>> len(r'\b')
2

>> This calls re.sub with a pattern string object that contains two
>> characters, a backslash followed by an 'n'.  This combination *does*
>> have a special meaning to the sub function, which does it's own
>> translation of the pattern into a single newline character.  
>
> So when do I know when a raw string is treated as a raw string, and
> when it's not?

A raw string LITERAL is always treated as a raw string LITERAL when
the Python interpreter turns it into a string OBJECT.  I used the
capitalised words very deliberately and precisely, yet you seem to
have managed to conflate them again.  Please don't.  How the literal
is interpreted is up to the Python interpreter.  How the object is
interpreted is up to the thing doing the interpretation, in this
case the re.sub() function.

How do you know how a string object is going to be treated by any
given function?  Read the Fine Manual for that function.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list