繁体   English   中英

使用Python 2.7.10解码ASCII字符串

[英]Decode a ASCII string with Python 2.7.10

我是Python的新手,所以我可能仍然会犯很多新手错误。

我正在比较Python中两个看似匹配的字符串,但始终返回false。 当我检查对象的表示形式时,我发现其中一个字符串是用ASCII编码的。

第一个字符串的表示形式返回:

'\x00"\x00i\x00t\x00i\x00n\x00e\x00r\x00a\x00r\x00y\x00_\x00o\x00p\x00t\x00i\x00o\x00n\x00s\x00_\x00s\x00e\x00a\x00r\x00c\x00h\x00_\x00b\x00u\x00t\x00t\x00o\x00n\x00"\x00 \x00=\x00 \x00"\x00L\x00a\x00u\x00n\x00c\x00h\x00 \x00t\x00h\x00e\x00 \x00s\x00e\x00a\x00r\x00c\x00h\x00"\x00;\x00'

当第二个字符串的表示形式返回时:

"itinerary_options_search_button" = "Launch the search";

我试图弄清楚如何解码第一个字符串以获得第二个字符串,以便我对两者的比较能够匹配。 当我用第一个字符串解码时

string.decode('ascii')

我得到一个unicode对象。 我不确定该怎么做才能得到解码后的字符串。

您的第一个字符串似乎有一些问题。 我不完全确定为什么会有这么多的空字符( \\x00 ),但是无论哪种方式,我们都可以编写一个函数来清除它们:

s_1 = '\x00"\x00i\x00t\x00i\x00n\x00e\x00r\x00a\x00r\x00y\x00_\x00o\x00p\x00t\x00i\x00o\x00n\x00s\x00_\x00s\x00e\x00a\x00r\x00c\x00h\x00_\x00b\x00u\x00t\x00t\x00o\x00n\x00"\x00 \x00=\x00 \x00"\x00L\x00a\x00u\x00n\x00c\x00h\x00 \x00t\x00h\x00e\x00 \x00s\x00e\x00a\x00r\x00c\x00h\x00"\x00;\x00'
s_2 = '"itinerary_options_search_button" = "Launch the search";'

def null_cleaner(string):
    new_string = ""
    for char in string:
        if char != "\x00":
            new_string += char
    return new_string

print(null_cleaner(s_1) == null_cleaner(s_2))

健壮性稍差的方法是简单地拼接字符串以删除所有其他字符(恰好是\\x00 ):

s_1 = '\x00"\x00i\x00t\x00i\x00n\x00e\x00r\x00a\x00r\x00y\x00_\x00o\x00p\x00t\x00i\x00o\x00n\x00s\x00_\x00s\x00e\x00a\x00r\x00c\x00h\x00_\x00b\x00u\x00t\x00t\x00o\x00n\x00"\x00 \x00=\x00 \x00"\x00L\x00a\x00u\x00n\x00c\x00h\x00 \x00t\x00h\x00e\x00 \x00s\x00e\x00a\x00r\x00c\x00h\x00"\x00;\x00'
s_2 = '"itinerary_options_search_button" = "Launch the search";'

print(s_1[1::2] == s_2)

...以ASCII编码。

 [lots of NULs] 

不。

>>> '\x00"\x00i\x00t\x00i\x00n\x00e\x00r\x00a\x00r\x00y'.decode('utf-16be')
u'"itinerary'

当然,您的数据还有一个额外的NUL会破坏它。 清理完之后,您应该可以毫无问题地对其进行解码。

暂无
暂无

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

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