恢复字符串中的 unicode 转义编码 (Python3)

Revert unicode escape encoding in string (Python3)

我有一个包含换行符的字符串 my_string。因此,如果打印,它将引入一个新行。

最初,我my_string.encode('unicode_escape').decode("utf-8")

其中 print(my_string.encode('unicode_escape').decode("utf-8")) 给出 \n

print (repr(my_string)) 给出 '\n'.

然后,我想做的是将其转换回原始状态,以便打印换行符,即 my_string 不显示换行符 \n\n但简单地引入一个新行。

我搜索了 encodedecode 但不知道该怎么做。

由于您首先使用 unicode_escape 编码,然后使用 utf-8 解码,因此逆运算将是各个操作的逆运算,顺序相反:

>>> x = '\n'
>>> y = x.encode('unicode_escape').decode('utf-8')
>>> y.encode('utf-8').decode('unicode_escape')
'\n'

(socks/shoes原则:先穿袜子再穿鞋;要解开先脱鞋再脱袜子。)