26

I have a list of unicode objects and want to encode them to utf-8, but encoding doesn't seem to work.

the code is here :

>>> tmp = [u' test context']
>>> tmp.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'encode'
>>>

I can't understand why there is no attribute encode

Antoine Pinsard
  • 28,811
  • 7
  • 58
  • 82
mt0s
  • 5,681
  • 10
  • 39
  • 53

2 Answers2

38

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

Mikel
  • 23,754
  • 8
  • 63
  • 66
  • 1
    **tmp is not a string. It contains a (Unicode) string.** yeap u r absolute right !! thnx a lot! – mt0s Feb 20 '11 at 00:09
10

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]
Prakhar Agarwal
  • 2,470
  • 27
  • 31