我有一段代码,其中包含以十进制书写的 UTF-8 转义序列的字符串,例如
my_string = "Hello\035"
这应该被解释为
Hello#
我不介意解析十进制值,到目前为止,我已经对整个字符串使用了类似的方法,这似乎效果最好(没有错误并且做了一些事情):
print(codecs.escape_decode(my_string)[0].decode("utf-8"))
但是编号似乎很不对劲,因为我必须使用\043 转义序列才能正确解码井号标记 (#),并且对于所有其他字符都是相同的。
最佳答案
您无法明确地检测并替换字符串文字中的所有 \ooo
转义序列,因为在第一行代码运行之前,这些转义序列将不可挽回地替换为其相应的字符值。就 Python 而言,"foo\041"
和 "foo!"
100% 相同,并且无法确定前一个对象是用转义序列,而后者不是。
如果您对输入数据的形式有一定的灵活性,那么您仍然可以做您想做的事情。例如,如果允许您使用原始字符串而不是常规字符串,则在运行时之前,r"Hello\035"
不会被解释为“Hello,后跟哈希标记”。它将被解释为“Hello,后跟反斜杠,后跟 0 3 和 5”。由于数字字符仍然可以访问,因此您可以在代码中操作它们。例如,
import re
def replace_decimal_escapes(s):
return re.sub(
#locate all backslashes followed by three digits
r"\\(\d\d\d)",
#fetch the digit group, interpret them as decimal integer, then get cooresponding char
lambda x: chr(int(x.group(1), 10)),
s
)
test_strings = [
r"Hello\035",
r"foo\041",
r"The \040quick\041 brown fox jumps over the \035lazy dog"
]
for s in test_strings:
result = replace_decimal_escapes(s)
print("input: ", s)
print("output: ", result)
结果:
input: Hello\035
output: Hello#
input: foo\041
output: foo)
input: The \040quick\041 brown fox jumps over the \035lazy dog
output: The (quick) brown fox jumps over the #lazy dog
作为一个奖励,如果您通过 input()
获取输入字符串,此方法也适用,因为用户在该提示中键入的反斜杠不会被解释为转义序列。如果您执行 print(replace_decimal_escapes(input()))
并且用户键入“Hello\035”,则输出将是所需的“Hello#”。
关于python - 如何正确解码以十进制书写的字符串中的转义序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54866881/