2

I have a unicode string like this

mm = u'A\xe2\x80\x8ct\xe2\x80\x8ch\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8cl\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8ce\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8ct\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8ci\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8cc\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c Bilbao (n)\tC\xe2\x80\x8cD\xe2\x80\x8c \xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8cM\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8ci\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8cr\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8ca\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8cn\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8c\xe2\x80\x8cdes'

I want to print it out to something like A‌t‌h‌‌‌‌‌‌l‌‌‌e‌‌‌‌t‌‌‌‌‌‌‌i‌‌‌‌‌c‌‌‌‌‌‌‌‌‌‌ Bilbao (n) but don't know how? I've try unicode(mm.encode("utf-8"), 'string-escape'), but it does not work in this case.

Edit: @Ignacio Vazquez-Abrams is right, and there are some problem with PyCharm console, it display unicode string like enter image description here

secmask
  • 7,649
  • 5
  • 35
  • 52

1 Answers1

3

You need to undo the incorrect encoding first.

>>> u'A\xe2\x80\x8ct\xe2\x80\x8ch...\xe2\x80\x8cdes'.encode('latin-1').decode('utf-8')
u'A\u200ct\u200ch\u200c\u200c\u200c\u200c\u200c\u200cl\u200c\u200c\u200ce\u200c\u200c\u200c\u200ct\u200c\u200c\u200c\u200c\u200c\u200c\u200ci\u200c\u200c\u200c\u200c\u200cc\u200c\u200c\u200c\u200c\u200c\u200c\u200c\u200c\u200c\u200c Bilbao (n)\tC\u200cD\u200c \u200c\u200c\u200c\u200c\u200c\u200cM\u200c\u200c\u200ci\u200c\u200c\u200c\u200cr\u200c\u200c\u200c\u200c\u200c\u200c\u200ca\u200c\u200c\u200c\u200c\u200cn\u200c\u200c\u200c\u200c\u200c\u200c\u200c\u200c\u200c\u200cdes'
>>> print u'A\xe2\x80\x8ct\xe2\x80\x8ch...\xe2\x80\x8cdes'.encode('latin-1').decode('utf-8')
A‌t‌h‌‌‌‌‌‌l‌‌‌e‌‌‌‌t‌‌‌‌‌‌‌i‌‌‌‌‌c‌‌‌‌‌‌‌‌‌‌ Bilbao (n)    C‌D‌ ‌‌‌‌‌‌M‌‌‌i‌‌‌‌r‌‌‌‌‌‌‌a‌‌‌‌‌n‌‌‌‌‌‌‌‌‌‌des
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • did you mean `u'A\u200ct\u200ch...`.encode('latin-1').decode('utf-8'). if that, I got this message `UnicodeEncodeError: 'ascii' codec can't encode character u'\u200c' in position 1: ordinal not in range(128)` – secmask Oct 09 '13 at 17:53
  • The only difference between the two commands is that the second prints the string. – Ignacio Vazquez-Abrams Oct 09 '13 at 17:54
  • 1
    @secmask: you also probably want to get rid of rubbish after the conversion: `mm=mm.replace(u'\u200c', '')` – georg Oct 09 '13 at 18:17