简体   繁体   English

如何将'\\ xff \\ xfe'转义为可读字符串

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

i see a string in this code: 我在这段代码中看到一个字符串:

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

i don't know what '\\xff\\xfe' is, 我不知道'\\ xff \\ xfe'是什么,

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 谢谢

'\\xFF' means the byte with the hex value FF. '\\ xFF'表示十六进制值为FF的字节。 '\\xff\\xfe' is a byte-order mark: http://en.wikipedia.org/wiki/Byte_order_mark '\\ xff \\ xfe'是字节顺序标记: 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. 您也可以将其表示为两个单独的字符,但这可能不会告诉您任何有用的信息。

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

What is the connection between "i don't know what '\\xff\\xfe' is" and "so i want to escape it"? “我不知道什么'\\ xff \\ xfe'是”和“所以我想逃避它”之间的联系是什么? 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. 如果你给出比data[:2] == '\\xff\\xfe'更多的上下文(前后几行),那将会有很大的帮助...但是看起来它正在测试是否前两个字节data可能代表UTF-16 littleendian字节顺序标记。 In that case you could do something like: 在这种情况下,您可以执行以下操作:

UTF16_LE_BOM = "\xff\xfe"

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

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. 您应该了解您正在使用字符串不是字节流,并且有一些您无法接受的字符,首先是0x00 - 以及您的示例恰好是BOM序列。

So if you need to include non-valid strings characters (unicode or ascii) you will have to stop using strings for this. 因此,如果您需要包含无效的字符串字符(unicode或ascii),则必须停止使用字符串。

Take a look at PEP-0358 看看PEP-0358

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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