views:

92

answers:

4

I have a string that after print is like this: \x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71

But I want to change this string to "\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71" which is not printable (it is necessary to write to serial port). I know that it ist problem with '\'. how can I replace this printable backslashes to unprintable?

A: 

You are confusing the printable representation of a string literal with the string itself:

>>> c = '\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71'
>>> c
'M\xff\xfd\x00\x02\x8f\x0e\x80fHq'
>>> len(c)
11
>>> len('\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71')
11
>>> len(r'\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71')
44
msw
A: 
your_string.decode('string_escape')
John Machin
Thx! It is he solution of my problem
Carolus89
Any reason for accepting the 3rd correct answer?
John Machin
No idea, maybe because I included a link? We were all within a minute or so ;-) (honestly: I found some others clearer than mine, and quality, not speed, should warrant a checked answer).
Abel
+2  A: 

Use decode():

>>> st = r'\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71'
>>> print st
\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71
>>> print st.decode('string-escape')
MÿýfHq

That last garbage is what my Python prints when trying to print your unprintable string.

ptomato
+3  A: 

If you want to decode your string, use decode() with 'string_escape' as parameter which will interpret the literals in your variable as python literal string (as if it were typed as constant string in your code).

mystr.decode('string_escape')
Abel
It was help me. My problem is resolved. Thanks a lot ;)
Carolus89