简体   繁体   中英

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?

如果要解码字符串,请使用带有'string_escape'作为参数的decode() ,它将变量中的文字解释为python文字字符串(就像在代码中键入为常量字符串一样)。

mystr.decode('string_escape')

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.

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
your_string.decode('string_escape')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM