在python 3中解码(unicode_escape)一个字符串 [英] decode(unicode_escape) in python 3 a string

查看:1276
本文介绍了在python 3中解码(unicode_escape)一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了此解决方案,但没有

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

I've an escaped string of this kind: str = "Hello\\nWorld" and I want to obtain the same string unescaped: str_out = Hello\nWorld

我尝试过此操作没有成功: AttributeError:'str'对象没有属性'decode'

I tried with this without succes: AttributeError: 'str' object has no attribute 'decode'

这里是我的示例代码:

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


推荐答案

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

decode applies to bytes, which you can create by encoding from your string.

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

I would encode (using default) then decode with 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 3中解码(unicode_escape)一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆