1

How do you "just print" a list containing unicode in Python3?

In Python2.*, I could simply do:

text = ['\u2014']
print(text)

But in Python3, this fails with the notorious error:

UnicodeEncodeError: 'ascii' codec can't encode character '\u2014' in position 2: ordinal not in range(128)

Unfortunately, the normal recommendations to use str() fail because this only works with bytes in Python3, not lists:

>>> print(str(text, encoding='utf-8', errors='ignore'))
TypeError: coercing to str: need a bytes-like object, list found
6
  • How did it not work? repl.it/Hx2H , it seems fine when running the code from repl.it Commented May 14, 2017 at 21:54
  • 1
    The first question to ask is why your stdout is ASCII. Look into changing your locale to use UTF-8. But if ASCII is your only choice, you can set the environment variable PYTHONIOENCODING=:backslashreplace. Commented May 14, 2017 at 21:59
  • @eryksun, Please submit an answer as an answer, not a comment. Commented May 18, 2017 at 18:31
  • Feel free to write and accept your own answer. Commented May 18, 2017 at 22:32
  • @eryksun, Why the passive aggressiveness? I'm trying to help you out and give you credit. Just use the site as intended and submit an answer. Commented May 19, 2017 at 9:18

1 Answer 1

1

To get equivalent behavior to Python 2 for printing lists in Python 3, use ascii():

>>> text = ['\u2014']
>>> print(ascii(text))
['\u2014']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.