带反斜杠的字符串的多重转换

Multiple transformations of a string with backslashes

我对 Python 中的字符串编码感到完全困惑。我阅读了许多其他答案,但 none 表明,下面代码的最后三行中到底发生了什么:

filename = "/path/to/file.txt" #textfile contains only the string "\bigcommand"

with open(filename,'r') as f:
    file = list(f)

val = file[0]                         #val = '\bigcommand\n'
valnew = val.encode('unicode-escape') #valnew = b'\\bigcommand\n'
valnewnew = str(valnew,'utf-8')       #valnewnew = '\\bigcommand\n'

为什么 valnew 变量突然变成字节串了?我以为它会和以前一样 - 但只是转义字符加倍?

为了获得 valnewnew 的输出,是否有比复杂的最后三行更短的方法?

这将为您提供 valnewnew 的输出:

val = file[0].encode('unicode-escape').decode()
with open('t', 'r') as f:
    file = list(f)

    val = file[0].encode('unicode-escape').decode() # value: '\\bigcommand\n'

当您在 python3.x 中对字符串进行编码时,您将字符串编码为字节,随后需要对其进行解码以返回字符串。

如果你对你正在尝试做的事情有一些了解,我可以尝试扩展。