0
votes

Say we have a string:

s = '\xe5\xaf\x92\xe5\x81\x87\\u2014\\u2014\xe5\x8e\xa6\xe9\x97\xa8'

Somehow two symbols, '—', whose Unicode is \u2014 was not correctly encoded as '\xe2\x80\x94' in UTF-8. Is there an easy way to decode this string? It should be decoded as 寒假——厦门

Manually using the replace function is OK:

t = u'\u2014'
s.replace('\u2014', t.encode('utf-8')
print s

However, it is not automatic. If we extract the Unicode,

index = s.find('\u')
t = s[index : index+6]

then t = '\\u2014'. How to convert it to UTF-8 code?

1
More code required. How are you making a UTF-8 string, with partially converted Unicode literals? It looks like you've got something fundamentally wrong with your other code that you should fix rather than hack around it - Alastair McCormack
Some formats can encode strings like this, eg. JSON is a common one these days. If you're trying to parse a JSON string, use a json parser. - roeland

1 Answers

0
votes

You're missing extra slashes in your replace()

It should be:

s.replace("\\u2014", u'\u2014'.encode("utf-8") )

Check my warning in the comments of the question. You should not end up in this situation.