Python UnicodeEncodeError:“ascii”编解码器无法对位置0中的字符进行编码:序号不在范围(128)内

2024-04-25 19:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.7中,当尝试强制转换类型以确保其与输出模式匹配时,请参见以下错误。

UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) Tried to find why and reproduced the error in Jupiter. By simply typing in.

str(u'\u2013')

如何将类型转换为可以处理此类错误的字符串?谢谢!


Tags: toin类型错误asciinotpositionrange
3条回答

我会回答我自己的问题。找到一个重复的问题。stackoverflow.com/questions/9942594/

但是,对于简单性,这里有一个非常适合我的用例的优雅解决方案:

def safe_str(obj):
    try: return str(obj)
    except UnicodeEncodeError:
        return obj.encode('ascii', 'ignore').decode('ascii')
    return ""

safe_str(u'\u2013')

或者简单地使用:

u'\u2013'.encode('ascii', 'ignore')

对于版本2.7.x,默认情况下不设置编码。 请使用下面的代码作为程序的第一行

# -*- coding: utf-8 -*-
# Your code goes below this line

它应该能解决你的问题。

对于Python3.x,有默认的编码,因此不会有编码问题。

试试这个:

u'\u2013'.encode('utf-8')

相关问题 更多 >