将 "foo" 转换为“\x66\x6f\x6f”的最佳方法

Best way to convert "foo" into "\x66\x6f\x6f"

我正在寻找一种方法将字符串转换为 Python 中的转义十六进制表示形式,例如"foo" 变为 "\x66\x6f\x6f"

如果可以使用内置函数

>>> s = 'foo'
>>> print "".join([hex(ord(i)) for i in s]).replace('0x','\x')
\x66\x6f\x6f

ord

Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string

hex

Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x”

使用 hex 内置函数和生成器表达式:

>>> print ''.join('\'+hex(ord(char))[1:] for char in 'foo')
\x66\x6f\x6f
"".join(map(hex,map(ord, "foo"))).replace("0x","\x")

另一种使用 encode 并指定 "hex" (Python 2.7) 的方法:

"".join(r"\x" + char.encode("hex") for char in "foo")

打印:

\x66\x6f\x6f

Python3 中的编码方法似乎更棘手 - 您最好使用其他方法!

>>> import binascii
>>> "".join(r"\x" + h for h in (binascii.hexlify(c.encode()).decode() for c in "foo"))
\x66\x6f\x6f

你也可以使用str.format:

print("".join(["\x{:x}".format(ord(c)) for c in s]))

或者使用我认为最有效的地图:

print(("\x{:x}" * len(s)).format(*map(ord,s)))

\x66\x6f\x6f
\x66\x6f\x6f

其实这不是答案,只是比较以前的解决方案。

In [76]: # short string
In [77]: s = 'foo'

In [78]: # Alexander's solution
In [79]: timeit "".join(map(hex,map(ord, list(s)))).replace("0x","\x")
1000000 loops, best of 3: 1.89 µs per loop

In [80]: # Rawing's solution
In [81]: timeit ''.join(['\'+hex(ord(char))[1:] for char in s])
1000000 loops, best of 3: 1.22 µs per loop

In [82]: # Bhargav Rao's solution
In [83]: timeit ''.join('\'+hex(ord(char))[1:] for char in s)
100000 loops, best of 3: 2.05 µs per loop

In [84]: # huge string
In [85]: s = 'f' * 100000

In [86]: # Alexander's solution
In [87]: timeit "".join(map(hex,map(ord, list(s)))).replace("0x","\x")
100 loops, best of 3: 15.7 ms per loop

In [88]: # Rawing's solution
In [89]: timeit ''.join(['\'+hex(ord(char))[1:] for char in s])
10 loops, best of 3: 25 ms per loop

In [90]: # Bhargav Rao's solution
In [91]: timeit ''.join('\'+hex(ord(char))[1:] for char in s)
10 loops, best of 3: 28.8 ms per loop

In [92]:

In [115] # Padraic Cunningham's solution
In [116]: s = 'foo'

In [117]: timeit ("\x{:x}" * len(s)).format(*map(ord,s))
1000000 loops, best of 3: 1.57 µs per loop

In [118]: s = 'f' * 100000

In [119]: timeit ("\x{:x}" * len(s)).format(*map(ord,s))
10 loops, best of 3: 24.2 ms per loop

In [120]: