[英]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.