Escaping slashes (double backslash plague)
Harry George
harry.g.george at boeing.com
Mon Jan 19 07:27:27 EST 2004
Peter Hansen <peter at engcorp.com> writes:
> 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
Did someone already mention os.path? Since this is about filenames,
that is the best cross-platform colution.
--
harry.g.george at boeing.com
6-6M31 Knowledge Management
Phone: (425) 342-5601
More information about the Python-list
mailing list