2013-10-12 74 views
0

我的代碼是爲什麼我不能逃脫特殊字符

hexviewer.py:

def hex_viewer(filename): 
    data = open(filename,"rb").read() 
    listofhex = map(lambda x: b"%02X" % ord(x),data) 
    listofchar = map(lambda x: "%s" % x,data) 
    print "\n".join(["{0}\t{1}".format(" ".join(listofhex[x:x+10])," ".join(listofchar[x:x+10]) ) for x in xrange(0,len(listofhex),10)] ) 
hex_viewer("hexviewer.txt") 

和我的源文件

hexviewer.txt:

hello 
world 

輸出我認爲應該是

68 65 6C 6C 6F 20 0D 0A 77 6F h e l l o \r \n w o 
72 6C 64      r l d 

但輸出

68 65 6C 6C 6F 20 0D 0A 77 6F h e l l o 

w o 
72 6C 64 r l d 

我到底做錯了什麼?

編輯: 我很抱歉,但我試圖編輯我的代碼

listofchar = map(lambda x: "%s" % x,data) 

這裏

listofchar = map(lambda x: repr(r"%s") % x,data) 

但輸出is`

68 65 6C 6C 6F 20 0D 0A 77 6F 'h' 'e' 'l' 'l' 'o' ' ' ' 
' ' 
' 'w' 'o' 
72 6C 64 'r' 'l' 'd' 

和我嘗試

import re 
listofchar = map(lambda x: re.escape(r"%s") % x,data) 

輸出

68 65 6C 6C 6F 20 0D 0A 77 6F \h \e \l \l \o \ \ 
\ 
\w \o 
72 6C 64 \r \l \d 

和我嘗試

listofchar = map(lambda x: r"%s".replace("\\","\\\\") % x,data) 

輸出

68 65 6C 6C 6F 20 0D 0A 77 6F h e l l o 

w o 
72 6C 64 r l d 

許多方式,但我忘了

我很抱歉T^T

+2

你打算在一次打印出一個字符時,你希望兩個字符來自哪裏?你在哪裏做標題 – Mark

回答

0

您需要的是一種讓普通字符單獨保留但只編碼特殊字符的方法。

listofchar = map(lambda x: x.encode('unicode-escape'), data) 

注意,您可以使用列表理解,而不是map,這是做到這一點的首選方式。

listofchar = [x.encode('unicode-escape') for x in data] 
+0

中提到的逃生非常感謝你:) @Mark Ransom –