Two problems with backslashes

Quinn Dunkan quinn at
Wed Jul 4 21:54:10 EDT 2001

On 4 Jul 2001 16:34:43 GMT, Gustaf Liljegren <gustafl at> wrote:
>"Emile van Sebille" <emile at> wrote:
>>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
>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.

Try not to think of things in terms of python "adding" or "removing"
backslashes.  Python will never alter your strings (and won't even let you
change them).  However, it will interpret what you put in between ""s, just as
it interprets [1,2] as a list, math.pi as a number, and open('foo') as a file
object.  It needs some way of readably representing nonprintable characters,
and backslash is it.  When printing a string, exactly what is in the string
will be printed (after all, if it mangled strings, that would really screw up
writing a JPEG to disk).  However, the interactive prompt doesn't print
strings exactly, it prints a representation of them that will be easy for
python to parse (with doubled backslashes, among other things).  You may have
noticed that it will also put quotes around your string, even though those
aren't part of the string.  For example:

s = 'foo\\bar' # requires \\ because ''s interpret \s
s2 = raw_input('enter path: ') # doesn't require the user to double \s because
    # raw_input doesn't interpret what it reads (hence the raw part)
print s # prints foo\bar
print repr(s) # prints a python-readable representation of s, "foo\\bar"

And note that if you just type 's' at the interactive prompt, that's
like "print repr(s)".

More information about the Python-list mailing list