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

标签 python cryptography hex des

这里我想获取这种格式的文本:\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

最佳答案

使用 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)

关于python - 以十六进制形式显示而不是特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371348/

相关文章:

c# - 从 Java 到 C# 的函数

python - Python光标提取器生成器

java - RSA加密-字节数组和字符串之间的转换

cryptography - Code Golf : Diffie-Hellman key exchange

c - 如何在 C 中更改进程的十六进制转储

c# - 将二进制数转换为 ascii 字符

python - 关于 Josephus_problem

python - 渐近函数趋近于零的 float 问题 - Python

python - 如何防止 python urllib3 缓存响应

javascript - 加密随机生成 MIT 库 javascript