4

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?

3
  • .encode("utf-8") but how is the output identical in both prints if one causes an error? Commented Feb 15, 2015 at 19:34
  • @Karl Knechtel My question was in title... but someone was change my title :) I ask why the first print was with error when second is ok Commented Feb 15, 2015 at 19:59
  • Yes, the question should not have been deleted in the edit, still I like the title because it is much more specific than "What is wrong with..." which is too generic. I edited and put the question where it belongs (in the question body). Hope it's okay. Commented Feb 15, 2015 at 21:07

1 Answer 1

8

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.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.