如何编码和解码字符串以在 python 中喜欢“\x70\x61\x75\x6c”

How to encode and decode string to like "\x70\x61\x75\x6c" this in python

我有一些密钥要发送到服务器并想要它 encoded.The 最好的办法是使字符串像 ("\x70 \x61 \x75 \x6c") 并对其进行解码在 server.But 这里我不知道要将 p a u l(从 ("\x70 \x61 \x75 \x6c") 解码)转换为字符串。

我想这样做:- 保罗加密到 ("\x70 \x61 \x75 \x6c") 和 ("\x70 \x61 \x75 \x6c") 解密到 paul.Thats全部.

要将 p a u l 编码为 ("\x70 \x61 \x75 \x6c"),您可以使用:

s = 'p a u l'
encoded = '("%s")' % ''.join(['\x'+c.encode('utf-8').hex() if c != ' ' else c for c in s])

解码:

encoded = r'("\x70 \x61 \x75 \x6c")'
' '.join(bytearray.fromhex(x[2:]).decode() for x in encoded[2:-2].split(' '))