如何将Unicode字符串(包含额外的字符,如£$等)转换为Python字符串?
当前回答
在我的例子中,没有答案,因为我有一个包含unicode字符的字符串变量,这里解释的编码-解码都不起作用。
如果我在终点站做
echo "no me llama mucho la atenci\u00f3n"
or
python3
>>> print("no me llama mucho la atenci\u00f3n")
输出是正确的:
output: no me llama mucho la atención
但是使用脚本加载这个字符串变量不起作用。
我的案子就是这么办的,说不定能帮到谁
string_to_convert = "no me llama mucho la atenci\u00f3n"
print(json.dumps(json.loads(r'"%s"' % string_to_convert), ensure_ascii=False))
output: no me llama mucho la atención
其他回答
在我的例子中,没有答案,因为我有一个包含unicode字符的字符串变量,这里解释的编码-解码都不起作用。
如果我在终点站做
echo "no me llama mucho la atenci\u00f3n"
or
python3
>>> print("no me llama mucho la atenci\u00f3n")
输出是正确的:
output: no me llama mucho la atención
但是使用脚本加载这个字符串变量不起作用。
我的案子就是这么办的,说不定能帮到谁
string_to_convert = "no me llama mucho la atenci\u00f3n"
print(json.dumps(json.loads(r'"%s"' % string_to_convert), ensure_ascii=False))
output: no me llama mucho la atención
下面是一个示例代码
import unicodedata
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')
>>> text=u'abcd'
>>> str(text)
'abcd'
如果字符串只包含ascii字符。
好吧,如果你愿意/准备切换到Python 3(由于与一些Python 2代码向后不兼容,你可能不会切换到Python 3),你不需要做任何转换;Python 3中的所有文本都用Unicode字符串表示,这也意味着不再使用u'<text>'语法。实际上,您还拥有用于表示数据的字节字符串(可能是经过编码的字符串)。
http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit
(当然,如果你目前使用的是Python 3,那么问题很可能与你试图将文本保存到文件的方式有关。)
这里有一个例子:
>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if