gpt4 book ai didi

python - 将中文ascii字符串转换为中文字符串

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:59 31 4
gpt4 key购买 nike

我尝试使用sys模块设置默认编码来转换字符串,但它不起作用。

字符串是:

`\xd2\xe6\xc3\xf1\xba\xcb\xd0\xc4\xd4\xf6\xb3\xa4\xbb\xec\xba\xcf`

中文意思是益民核心增长混合。但是如何将其转换为中文字符串呢?

我尝试过:

>>> string = '\xd2\xe6\xc3\xf1\xba\xcb\xd0\xc4\xd4\xf6\xb3\xa4\xbb\xec\xba\xcf'
>>> print string.decode("gbk")
益民核心增长混合 # As you can see here, got the right answer
>>> new_str = string.decode("gbk")
>>> new_str
u'\u76ca\u6c11\u6838\u5fc3\u589e\u957f\u6df7\u5408' # It returns the another encode type.
>>> another = u"益民核心增长混合"
>>> another
u'\u76ca\u6c11\u6838\u5fc3\u589e\u957f\u6df7\u5408' # same as new_str

所以,我只是对这种情况感到困惑,为什么我可以打印 string.decode("gbk") 但 python 控制台中的 new_str 只是返回另一种编码类型?

我的操作系统是Windows 10,我的Python版本是Python 2.7。非常感谢!

最佳答案

你做得对。

在本例中,new_str 实际上是一个 unicode 字符串,由 u 前缀表示。

>>> new_str
u'\u76ca\u6c11\u6838\u5fc3\u589e\u957f\u6df7\u5408' # It returns the another encode type.

当你解码GBK编码的字符串时,你会得到一个unicode字符串。该字符串的每个字符都是一个 unicode 代码点,例如

>>> u'\u76ca'
u'\u76ca'
>>> print u'\u76ca'

>>> import unicodedata
>>> unicodedata.name(u'\u76ca')
'CJK UNIFIED IDEOGRAPH-76CA'

>>> print new_str
益民核心增长混合
>>> print repr(new_str)
u'\u76ca\u6c11\u6838\u5fc3\u589e\u957f\u6df7\u5408

这就是 Python 在解释器中显示 unicode 字符串的方式 - 它使用 repr 来显示它。但是,当您打印该字符串时,Python 会转换为您的终端的编码 (sys.stdout.encoding),这就是该字符串按您预期显示的原因。

所以,这并不是字符串的不同编码,而是 Python 在解释器中显示字符串的方式。

关于python - 将中文ascii字符串转换为中文字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763467/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com