0

I ran into some Unicode errors in Python trying to print some strings and I solved most of it using the following code from the second bullet point of the answer given in the following post: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

# -*- coding: utf-8 -*-
import sys

print sys.stdout.encoding
print u"Stöcker".encode(sys.stdout.encoding, errors='replace')
print u"Стоескер".encode(sys.stdout.encoding, errors='replace')

However, I get an error while trying to use this on a list object. It gives me an error that the list does not have the attribute "encode".

Does someone have a clean solution to get around this?

Any help is appreciated!

Community
  • 1
  • 1
Michael
  • 973
  • 12
  • 28
  • 3
    apply `encode()` to list items, not the list itself – Dušan Maďar May 15 '16 at 19:01
  • 2
    please add the output you get (the error text) and your python version. Works here... – Jörg Beyer May 15 '16 at 19:03
  • _'''It gives me an error that the list does not have the attribute "encode".'''_ That's because `list` does not have an `encode` method, that is a [method on a `str` or `unicode`](https://docs.python.org/2/library/stdtypes.html#str.encode) – Tadhg McDonald-Jensen May 15 '16 at 19:10
  • what do you expect to happen if you did `[1,2,3].encode(...)`? Encode only makes sense to happen on a string, not a list. If you want to encode each element then do that: `for i,item in enumerate(my_list): my_list[i] = item.encode(...)` or make a new list with encoded items with list comprehension: `[item.encode(...) for item in my_list]` – Tadhg McDonald-Jensen May 15 '16 at 19:13

1 Answers1

0

When you print a list, the routines that do the printing will take non-string objects and call their __str__ method to convert them to a string. But you are trying to call the decode method of a non-string object, and non-string objects don't have a decode method.

One way around this is to apply the unicode function to the list and then call the resulting string's decode method.

print unicode([u"Stöcker", u"Стоескер"]).encode(
               sys.stdout.encoding, errors='replace')

This should work with most objects.

holdenweb
  • 24,217
  • 7
  • 45
  • 67