Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String .format() vs. % formatting with Unicode data

With

print("    {:d}). {:s} ({:d})".format(i, account, num_char))

I get the error:

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

but when I change it to:

print "    %d). %s (%d)" % (i, account, num_char)

then there are no problem and output is identical with both prints.

So what is wrong in the first expression and why does it work in the second?

like image 810
XnIcRaM Avatar asked Feb 10 '23 22:02

XnIcRaM


1 Answers

In the first example, you are calling the format method of str object passing unicode arguments. This causes an error. You should use

print(u"    {:d}). {:s} ({:d})".format(i, account, num_char))

instead.

In the second one, you are using the % operator which automatically returns unicode when either format or object is unicode. From the docs:

  1. If the object or format provided is a unicode string, the resulting string will also be unicode.
like image 74
Selcuk Avatar answered Feb 13 '23 12:02

Selcuk