how to replace double backslash with one backslash in string...

Eric Brunel eric_brunel at
Thu Jul 1 13:29:06 CEST 2004

Vincent Texier wrote:
> Hello,
> I want to send 3 chars in hexa code to the serial port.
> So I type in a tkinter entry : "\x20\x01\x21"
> The string is set in a StringVar().
> When I read the stringVar, I get : "\\x20\\x01\\x21"
> The length is 12 and not 3 anymore.
> How can I replace the escape character from the string with the 
> corresponding char, and get my 3 char string back ?

You never had a 3 char string: the \ escapes are valid in python code, but not 
in strings read from the user by any means. Typing \x20 in a Tkinter entry is 
the same as reading a file containing the characters '\', 'x', '2' and '0': you 
get exactly these characters, not the character represented by this string if 
you had put it in your code.

> I've tried a re.sub(r'\\', chr(92)) but chr(92) is a double backslash 
> again.

No, it's not: you're confusing how it is represented ('\\') and what it is (a 
*single* back-slash). Try this:

 >>> s = '\\'
 >>> s
 >>> print s

Back-slash is an escape character, so you have to double it when you enter it. 
But '\\' is a string containing only one back-slash, as you can see when 
printing it.

If you're sure you'll never have any quote in the string, you can try to do 
eval("'%s'" % myStringVar.get())

 >>> s = r'\x20\x01\x21'
 >>> s
 >>> eval("'%s'" % s)
' \x01!'

Note that this may be dangerous, since the eval will take place in your program, 
so it can break things if you're not careful. Checking that it does not contain 
any quotes may be a good start.

- Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> -
PragmaDev : Real Time Software Development Tools -

More information about the Python-list mailing list