Two problems with backslashes

Peter Hansen peter at
Fri Jul 6 06:00:04 CEST 2001

Gustaf Liljegren wrote:
> "Emile van Sebille" <emile at> wrote:
> >
> >import getopt, sys
> >print getopt.getopt(sys.argv[1:], "")
> >
> >F:\Python21>python c:\test
> >([], ['c:\\test'])
[examples reinserted by peter at]
> >
> >So it appears to work here using getopt.  Something else must be going
> >on. Can you post an example that generates the string with the embedded
> >tabs?
> Thank you. I had no idea that Python would add the extra backslash
> automatically. Tried to isolate the problem before trying the whole thing
> on getopt. This solved the problem on a more appropriate level.

Gustaf, Python does _not_ "add the extra backslash".  What is 
shown above as ([], ['c:\\test']) is just a printable
*representation* of the content of the string, which actually
contains only a single backslash.

If you print a string directly (e.g. 'print "some text"')
then the actual sequence of bytes in the string is output,
and whatever non-printing characters (control characters) 
you may have will affect the output.

If instead you print a tuple or list containing a string
(or a tuple containing a list which contains a string
as in the above example), Python will print instead a 
special representation of the data, and any contained
strings will be printed with special control characters 
escaped so they don't mess up the output (and so that
the same data could be used as input to generate exactly
the same data again in certain ways).


>>> a = 'c:\\test'
>>> a
>>> print a
>>> print len(a)
>>> b = 'c:\test'
>>> b
>>> print b
c:      est
>>> print len(b)

The string 'a' contains seven bytes where the third byte
is a backslash.  The string 'b' contains only six bytes
where the third byte is the tab character (formed when
you use a backslash followed by a 't' in a string).

It looks like you solved the problem, but from your
message above it didn't sound like you had completely 
understood how string entry, string representations 
when printing, and raw strings all work in Python.
I hope this helps a little.

Peter Hansen, P.Eng.
peter at

More information about the Python-list mailing list