CarolusPl
CarolusPl

Reputation: 639

I want one backslash - not two

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?

Upvotes: 1

Views: 819

Answers (4)

Abel
Abel

Reputation: 57159

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')

Upvotes: 5

ptomato
ptomato

Reputation: 57870

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.

Upvotes: 2

John Machin
John Machin

Reputation: 82934

your_string.decode('string_escape')

Upvotes: 1

msw
msw

Reputation: 43487

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

Upvotes: 1

Related Questions