在Python中将字符串中的所有字符转换为ASCII十六进制

9 投票
5 回答
25960 浏览
提问于 2025-04-17 18:25

我在找一段Python代码,想把一个普通字符串里的所有字符(也就是所有的英文字母)转换成ASCII的十六进制格式。 我不太确定我是不是问错了,因为我一直在找这个,但就是找不到。

我可能只是没注意到答案,但我真的希望能得到一些帮助。

为了更清楚一点,比如把'Hell'转换成'\x48\x65\x6c\x6c'。

5 个回答

5

类似这样的内容:

>>> s = '123456'
>>> from binascii import hexlify
>>> hexlify(s)
'313233343536'
6

根据Jon Clements的回答,试试在python3.7上运行这些代码。
我遇到了这样的错误:

>>> s = '1234'    
>>> hexlify(s)    
Traceback (most recent call last):    
  File "<pyshell#13>", line 1, in <module>    
    hexlify(s)    
TypeError: a bytes-like object is required, not 'str'

通过以下代码解决了这个问题:

>>> str = '1234'.encode()    
>>> hexlify(str).decode()   
'31323334'
7

我想用这段代码 ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring) 可以解决这个问题...

>>> mystring = "Hello World"
>>> print ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring)
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64

撰写回答