how can i escape '\xff\xfe' to a readable string

自闭症网瘾萝莉.ら 提交于 2019-12-18 18:36:11

问题


i see a string in this code:

data[:2] == '\xff\xfe'

i don't know what '\xff\xfe' is,

so i want to escape it ,but not successful

import cgi
print cgi.escape('\xff\xfe')#print \xff\xfe

how can i get it.

thanks


回答1:


You cannot escape or encode an invalid string.

You should understand that you are working with strings and not byte streams and there are some characters you cannot accept in them, first of them being 0x00 - and also your example that is happening to be a BOM sequence.

So if you need to include non-valid strings characters (unicode or ascii) you will have to stop using strings for this.

Take a look at PEP-0358




回答2:


'\xFF' means the byte with the hex value FF. '\xff\xfe' is a byte-order mark: http://en.wikipedia.org/wiki/Byte_order_mark

You could also represent it as two separate characters but that probably won't tell you anything useful.




回答3:


>>> print '\xff\xfe'.encode('string-escape')
\xff\xfe



回答4:


What is the connection between "i don't know what '\xff\xfe' is" and "so i want to escape it"? What is the purpose of "escaping" it?

It would help enormously if you gave a little more context than data[:2] == '\xff\xfe' (say a few line before and after) ... however it looks like it is testing whether the first two bytes of data could possibly represent an UTF-16 littleendian byte order mark. In that case you could do something like:

UTF16_LE_BOM = "\xff\xfe"

# much later
if data[:2] == UTF16_LE_BOM:
    do_something()


来源:https://stackoverflow.com/questions/1979171/how-can-i-escape-xff-xfe-to-a-readable-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!