python - 在python 3中解码(unicode_escape)一个字符串

标签 python escaping

<分区>

我检查过 this solution但它在 python3 中不起作用。

我有一个这样的转义字符串:str = "Hello\\nWorld" 我想获得相同的未转义字符串:str_out = Hello\nWorld

我试过这个但没有成功:AttributeError: 'str' object has no attribute 'decode'

这里是我的示例代码:

str = "Hello\\nWorld"
str.decode('unicode_escape')

最佳答案

decode 适用于 bytes,您可以通过对字符串进行编码来创建它。

我会编码(使用默认值)然后使用unicode-escape解码

>>> s = "Hello\\nWorld"
>>> s.encode()
b'Hello\\nWorld'
>>> s.encode().decode("unicode-escape")
'Hello\nWorld'
>>> print(s.encode().decode("unicode-escape"))
Hello
World
>>> 

关于python - 在python 3中解码(unicode_escape)一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48908131/

相关文章:

在嵌入式 arm asm - armcc 中使用立即值的 C 宏

algorithm - 如何实现转义

python - 将带有反斜杠后跟数字的字符串转换为路径

android - Android中的strings.xml文件出错

python - 如何访问对象中的对象方法?

python - Linux中如何将一行数据复制到接下来N行的最后一列?

python - 无法在Python中导入C扩展文件

python - 使用 scrapy 选择单选按钮

python - 从python中的压缩文件中逐行读取

perl - 如何安全地将带空格的文件名传递给 Perl 中的外部命令?