我正在寻找可以在Python中将普通字符串(所有英文字母)中的所有字符转换为ASCII十六进制的Python代码。我不确定我是否用错了方式,因为我一直在搜索,但似乎找不到这个。
我可能只是忽略了答案,但我希望得到一些帮助。
只是为了澄清,从'Hello'到'\ x48 \ x65 \ x6c \ x6c'
''.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
基于Jon Clements的答案,尝试在Python 3.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'
Something like:
>>> s = '123456'
>>> from binascii import hexlify
>>> hexlify(s)
'313233343536'
尝试:
" ".join([hex(ord(x)) for x in myString])
从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'
。
''.join([r'\x%x'%ord(c) for c in mystring])
至少可以在Python2.4中运行(无论何时引入了列表推导式)——而且从性能的角度来看,与Cpython中的生成器表达式相比,连接列表推导式总是更好的选择……因此,使用它并没有什么坏处,除了有点丑陋。 - mgilson