以十六进制形式而不是特殊字符显示

2024-05-18 17:42:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我想得到以下格式的文本:\x10\x11\x12\x13\x15\x14\x16\x17,当显示控制台时,我如何得到它

   from pyDes import *
   import base64,string,random
   letters = [chr(i) for i in range(0,128)]
   key = '12345678'
   obj1= des(key, ECB)
   obj2 = des(key, ECB)
   text = '\x10\x11\x12\x13\x15\x14\x16\x17'
   print len(text)
   cipher_text = obj1.encrypt(text)
   decoded_text= obj2.decrypt(cipher_text)

   print; print 'plain text: ', text
   print; print 'Actual key: ', key 
   print; print 'Cipher text: ',cipher_text

Tags: keytextimportcipherprintx10desx17
1条回答
网友
1楼 · 发布于 2024-05-18 17:42:00

使用repr()%r字符串格式占位符打印表示:

print '\nplain text: %r' % text
print '\nActual key: %r' % key 
print '\nCipher text: %r' % cipher_text

或者可以显式地将文本编码为string_escape编码:

print '\nplain text:', text.encode('string_escape')
print '\nActual key:', key.encode('string_escape')
print '\nCipher text:', cipher_text.encode('string_escape')

这两种方法都不会将所有字节转换为\xhh转义序列,只转换可打印ASCII字符范围之外的转义序列。你知道吗

要将所有字符转换为转义序列,必须使用以下命令:

def tohex(string):
    return ''.join('\\x{:02x}'.format(ord(c)) for c in string)

然后呢

print '\nplain text:', tohex(text)
print '\nActual key:', tohex(key)
print '\nCipher text:', tohex(cipher_text)

相关问题 更多 >

    热门问题