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

问题描述 投票:0回答:5

只是在寻找可以将所有字符从普通字符串(所有英文字母)转换为 python 中的 ascii 十六进制的 python 代码。我不确定我是否以错误的方式问这个问题,因为我一直在寻找这个但似乎找不到这个。

我一定只是忽略了答案,但我希望得到一些帮助。

澄清一下,从“地狱”到“\x48\x65\x6c\x6c”

python ascii
5个回答
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

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'

4
投票

类似的东西:

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

3
投票

尝试:

" ".join([hex(ord(x)) for x in myString])

0
投票

从 Python 3.5 开始,您可以使用 hex 方法将字符串转换为十六进制值(生成字符串):

str = '1234'
str.encode().hex()
# '31323334'

知道可以用另一种方式解决它:

str = '1234'
hexed = str.encode().hex()
hex_values = [hexed[i:i+2] for i in range(0, len(hexed), 2)] # every 2 chars
delim = r'\x'

res = delim + delim.join(hex_values)
print(res)
# '\x31\x32\x33\x34'

注意: 如果将字符串定义为字节,则可以省略

encode()
方法:
str = b'1234'
.

© www.soinside.com 2019 - 2024. All rights reserved.