本文介绍了为什么在格式字符串中的python warnings.formatwarning中会得到编码错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此行上遇到编码错误:

I get encoding error on this line:

s =  "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)

UnicodeEncodeError:'ascii'无法在位置44中编码字符u'\xc4':序号不在范围(128)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)

我尝试通过将所有参数组合传递给字符串格式,但最接近的是ascii解码错误(通过同时传递unicode和高ascii字符串,强制将字符串转换为unicode,使用ascii解码器。

I tried to reproduce this error by passing all combinations of parameters to string format, but closest I got was "ascii decode" error (by passing unicode and high ascii string simultaneously, which forced conversion of string to unicode, using ascii decoder.

但是,我没有设法得到ascii encode错误,任何人都有想法?

However, I did not manage to get "ascii encode" error. Anybody has an idea?

推荐答案

强制参数:

s = u"\u00fc"
print str(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 0: ordinal not in range(128)

这是因为您的一个参数是一个对象(不是任何类型的字符串),Python调用 str()。有两种解决方案:对于格式( s = u%s ...)使用unicode字符串,或者使用 repr )

This happens because one of your arguments is an object (not a string of any kind) and Python calls str() on it. There are two solutions: Use a unicode string for the format (s = u"%s...") or wrap each argument with repr().

这篇关于为什么在格式字符串中的python warnings.formatwarning中会得到编码错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 09:41