使用在运行时之前未知的转义值(变量)构造字符串

Constructing strings with escaped values (variables) that are unknown until runtime

假设我在字符串中有一个转义的十六进制值:

val = "\x70"

和函数

def foo(input):
  for byte in bytes(input, "utf-8"):
    print(byte)

如果我打电话

foo(val) #prints 112

函数按预期运行。但是,如果我不知道要转义的十六进制代码的值,但又想转义它并以相同的方式遍历它怎么办?

unknown_until_runtime = "70"
val = "\x" + unknown_until_runtime

结果

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

我可以选择转义转义字符,但这会破坏 foo() 中迭代器的功能:

unknown_until_runtime = "70"
val = "\x" + unknown_until_runtime
foo(val) #prints 92 120 55 48

这种“字符串构造方法”并没有像预期的那样转义整个字节,而是不转义任何内容,只是创建了一个“字符字符串”,它无法按我想要的方式运行。对于我的一生,我找到了一种方法来获取这个“转义字节字符串”,直到运行时这些值都是未知的。有什么建议吗?

如果您将函数更改为以下内容,它应该可以工作:

def foo(input_str)
    for byte in bytes('\x' + input_str, 'utf-8').decode('unicode_escape'):
        print(byte)

解决方案灵感来自 this answer