Escaping slashes (double backslash plague)
Peter Hansen
peter at engcorp.com
Mon Jan 19 10:48:36 EST 2004
Aloysio Figueiredo wrote:
>
> I need to replace every ocurrence of '/' in s by '\/'
> in order to create a file named s. My first attempt
> was:
>
> s = '\/'.join(s.split('/'))
>
> but it doesn't work:
>
> >>> s = 'a/b'
> >>> s = '\/'.join(s.split('/'))
> >>> s
> 'a\\/b'
> >>> repr(s)
> "'a\\\\/b'"
> >>>
>
> '\/'.join() escapes the backslashes and I don't know why.
It does not, although *you* are not escaping the backslash
yourself, and that is dangerous. Get in the habit of always
escaping your own backslashes, so that if you ever happen
to use a backslash followed by one of the characters which _is_
a valid escape sequence, you won't get confused.
'\/' == '\\/'
but
'\t' != '\\t'
The first example shows two ways of writing a string with the blackslash
character followed by a forward slash. The second example shows a TAB
character on the left, but a backslash plus the letter 't', on the right.
As for your apparent automatic escaping of backslashes: when you show
results in an interactive session by just typing the expression, such as
when you do ">>> s" you will see the repr() of the value, not the actual
content. Use print instead and you'll see the difference:
>>> print s
This is all covered pretty well, I think, by the Python tutorials and
such. Have you gone through those?
-Peter
More information about the Python-list
mailing list