Why can I get an encoding error in the python.formatwarning warnings on the format string?


I get encoding error on this line:

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

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

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.

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

This happens when Python tries to coerce an argument:

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

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().