[Tutor] double backslash in Windows paths
magnus at thinkware.se
Sat May 1 12:21:56 EDT 2004
At 16:21 2004-04-30 -0700, tpc at csua.berkeley.edu wrote:
>hi everybody, what do you guys use to convert a Windows path, with single
>backslash, to double backslash ?
I don't understand what your problem is.
You typically don't convert strings to double up backslashes.
You use backslashes as escape characters in string lterals. This
means that the string literal "hello\tthere" in your Python source
code conweys the message to Python that you want the letters h, e,
l, l, o, followed by a TAB character and then there is t, h, e, r
and e in your string. There is no way you can change a tab character
to a backslash followed by a t by trying to change \ to \\.
So, if you type string literals, you either need to use raw strings,
such as in d = r"c:\this\there", or use double backslashes as in
d = "c:\\this\\there". Both those strings contain exactly the same
thing after the Python interpreter has parsed them. They contain
just what the first (raw) string suggests.
If you for instance read strings from files or from raw_input, this
is not an issue. You need to use eval() etc to make Python read \t
as if it would be a tab character.
Alternatively, you can use d = "c:/this/there" instead, and about
the whole issue.
The exception to this is when you will pass your strings to some
external program or library that expects strings with backslashes
being escapes, such as the regular expression library (re) or some
external OS command. In those cases, the string escapeas will be
interpreted twice, by two different systems, so that "\\t" will
be translated to "\t" and that will be translated to a tab in
the second step, and if you actually need "\t" after the second
step, you might need to write a string literal as "\\\\t" which
is the same as reading in a string containing \\t.
Confused now? ;^)
Magnus Lycka (It's really Lyckå), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language
More information about the Tutor