gpt4 book ai didi

python - 将转义字符添加到 Python 中的变量

转载 作者:行者123 更新时间:2023-11-28 18:28:10 25 4
gpt4 key购买 nike

我需要向要附加到另一个字符串的变量添加一个转义字符,并让它应用其效果。这是我的:

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 之外,我似乎无法在变量上使用它。

有什么建议吗?

最佳答案

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

import itertools
import binascii

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

这会将所有 hexpairs 批量解码为原始字节值(您想要的“转义”),因此 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('', '')

关于python - 将转义字符添加到 Python 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com