gpt4 book ai didi

python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xef in position 1

转载 作者:IT老高 更新时间:2023-10-28 21:07:21 24 4
gpt4 key购买 nike

我在尝试将字符串编码为 UTF-8 时遇到了一些问题。我尝试了很多东西,包括使用 string.encode('utf-8')unicode(string),但我得到了错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1: ordinal not in range(128)

这是我的字符串:

(。・ω・。)ノ

我不知道出了什么问题,知道吗?

编辑:问题是按原样打印字符串无法正确显示。另外,当我尝试转换它时出现这个错误:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)

最佳答案

这与您的终端编码未设置为 UTF-8 有关。这是我的终端

$ echo $LANG
en_GB.UTF-8
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(。・ω・。)ノ
>>>

在我的终端上,该示例适用于上述示例,但如果我摆脱 LANG 设置,它将无法正常工作

$ unset LANG
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
>>>

请查阅您的 linux 变体的文档,了解如何使此更改永久生效。

关于python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xef in position 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10561923/

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