在Python

时间:2016-09-22 22:15:25

标签: python

我需要为一个变量添加一个转义字符,我将它附加到另一个字符串并让它应用它的效果。这就是我所拥有的:

h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']

h3 = list(itertools.product(h1, h2))
h4 = []

for item in h3:
    h4.append(''.join(item))

temp = r'\x' + str(h4[0]) + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'

所以如果我有\ xh我需要带有十六进制值的字符hh但我似乎无法在python中找到除了\ x之外的任何内容,而我似乎无法在变量上使用它。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

重复int / chr次调用的一个更快的解决方案(假设您使用的不只是产生的第一个字节)是创建一个完整的十六进制字符串并一次解析它:

import itertools
import binascii

hexdigits = "123456789abcdef"
completehex = ''.join(map(''.join, itertools.product(hexdigits, repeat=2)))
completebytes = binascii.unhexlify(completehex)

这会将所有hexpair批量解码为原始字节值("转义"您想要),因此completebytes将为'\x00\x01\x02\x03...\xfd\xfe\xff'

当然,对于这种特殊情况(如果您的真正问题不是按顺序生成所有可能的字节值),您可以进一步简化它,因为您正在做的只是生成所有可能的字节值:

# Py3
completebytes = bytes(range(256))

# On Py2, bytes is alias for str, so must use bytearray first to accept iterable of int
completebytes = bytes(bytearray(range(256)))

或者,只是为了好玩,最快的方式滥用maketrans

# Py3:
completebytes = bytes.maketrans(b'', b'')  # Add .decode('latin-1') if you really want str

# Py2:
import string
completebytes = string.maketrans('', '')

答案 1 :(得分:0)

使用int()将十六进制值转换为整数,然后使用chr()将该数字转换为字符:

import itertools

hexdigits = "123456789abcdef"

for dig1, dig2 in itertools.product(hexdigits, hexdigits):
    char = chr(int(dig1 + dig2, 16))
    temp = char + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'

答案 2 :(得分:0)

要回答OP问题,这里有一种方法可以转换使用转义符号,一个包含两个十六进制数字的字符串

h = '11'
temp = eval( r"'\x" + h + "'" )

然而,这不是进行转换的最佳方式(请参阅其他答案)。我建议chr(int(h,16))。另一种方法是使用整数而不是字符串h=0x11temp = chr(h)