8

With the following code

lst = [u'\u5de5', u'\u5de5']
msg = repr(lst).decode('unicode-escape')
print msg

I got

[u'工', u'工']

How can I remove the leading u so that the content of msg is:

['工', '工']
gongzhitaao
  • 6,073
  • 3
  • 32
  • 44
  • What you are doing there gives me an `AttributeError`. – anon582847382 Mar 30 '14 at 15:42
  • gongzhitaao, what are you trying to achieve? – elbear Mar 30 '14 at 15:44
  • @LucianU Trying to remove the leading convert the unicode code point to characters but removing the leading `u`. – gongzhitaao Mar 30 '14 at 15:44
  • @gongzhitaao, I was asking for the higher purpose of your code. If you just want to print the characters, it's enough to do `for c in lst: print c.encode('utf-8')` – elbear Mar 30 '14 at 15:47
  • @LucianU Of course not :P. I have no problem printing out them while removing the leading `u`. I just need the unicode characters in a tring without `u`. :) – gongzhitaao Mar 30 '14 at 15:49
  • This is what I'm curious to know. Why do you need them without `u`? Why do you use the representation of a list as a string? – elbear Mar 30 '14 at 15:52
  • @LucianU See my updated post. – gongzhitaao Mar 30 '14 at 15:57
  • What you posted already works, so I don't understand the question. I think you don't understand how unicode/bytestrings work and this causes your confusion. – elbear Mar 30 '14 at 16:00
  • @LucianU It works, never mind. – gongzhitaao Mar 30 '14 at 16:02
  • Possible duplicate of [Easy way to convert a unicode list to a list containing python strings?](http://stackoverflow.com/questions/18272066/easy-way-to-convert-a-unicode-list-to-a-list-containing-python-strings) – Luke Taylor Feb 28 '16 at 20:17

1 Answers1

15
>>> import sys
>>> lst = [u'\u5de5', u'\u5de5']
>>> msg = repr([x.encode(sys.stdout.encoding) for x in lst]).decode('string-escape')
>>> print msg
['工', '工']
falsetru
  • 314,667
  • 49
  • 610
  • 551