将字符串字符表示为 python 中的十六进制值

Represent string characters as hex values in python


我试图用十六进制值表示给定的字符串,但失败了。
我试过这个:

# 1
bytes_str = bytes.fromhex("hello world")

# 2
bytes_str2 = "hello world"
bytes_str2.decode('hex')

第一个我得到"ValueError: non-hexadecimal number found in fromhex() arg at position 0" error
第二次我知道 str 没有 decode 属性。这是真的,但我在这里找到了它,所以我猜它值得一试。

我的目标是打印这样的字符串:\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00...

感谢您的帮助!

使用binascii

import binascii

value = "hello world"
print(binascii.hexlify(value.encode("utf-8")))  # b'68656c6c6f20776f726c64'
print(binascii.unhexlify(b'68656c6c6f20776f726c64').decode())  # hello world

print('\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64')  # hello world

bytes.fromhex() 需要一个内部包含十六进制数字的字符串,可能还有空格。
bytes.hex() 是从字节对象创建一串十六进制数字的

>>> hello='Hello World!'                 # a string
>>> hellobytes=hello.encode()
>>> hellobytes
b'Hello World!'                          # a bytes object
>>> hellohex=hellobytes.hex()
>>> hellohex
'48656c6c6f20576f726c6421'               # a string with hexadecimal digits inside
>>> hellobytes2=bytes.fromhex(hellohex)  # a bytes object again
>>> hello2=hellobytes2.decode()          # a string again
>>> hello2
'Hello World!'                           # seems okay

然而,如果你想要一个包含 \x 部分的实际字符串,你可能必须手动执行此操作,因此将连续的 hexstring 拆分为 digit-pairs,然后将 \x 他们之间:

>>> formatted="\x"+"\x".join([hellohex[i:i + 2] for i in range(0, len(hellohex), 2)])
>>> print(formatted)
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21