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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48347331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:40:06  来源:igfitidea点击:

Python UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128)

pythonstringpython-2.7unicodeencoding

提问by Bin

In Python 2.7, see the following error, when trying to cast type to ensure it matches the output schema.

在 Python 2.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.

UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) 试图找出原因并在 Jupiter 中重现错误。只需输入即可。

str(u'\u2013')

What is the way to cast type to string that can handle this type of error? Thanks!

将类型转换为可以处理此类错误的字符串的方法是什么?谢谢!

回答by akhilsp

Try this:

尝试这个:

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

回答by Bin

I will answer my own question. Found an duplicated question. stackoverflow.com/questions/9942594/

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

But for simplicity, here is an elegant solution that works well with my use case:

但为简单起见,这是一个适用于我的用例的优雅解决方案:

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

safe_str(u'\u2013')

Or simply use:

或者简单地使用:

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

回答by Ashish Bainade

For version 2.7.x ,encoding is not set by default. Please use below code as a first line of program

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

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

It should solve your problem.

它应该可以解决您的问题。

For python 3.x ,there is default encoding.hence there will be no issue of encoding.

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