Drake Guan
Drake Guan

Reputation: 15152

Convert u'\xe0' to '\u00E0' in Python 2.x?

In Python 2.x, how can I convert an unicode string (ex, u'\xe0') to a string (here I need it to be '\u00E0')?

To make it clearer. I do like to have '\u00E0', a string with length of 6. That is, ¥u is treated as 2 chars instead of one escaped char.

Upvotes: 3

Views: 2666

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

\u doesn't exist as a string escape sequence in Python 2.

You might mean a JSON-encoded string:

>>> s = u'\xe0'
>>> import json
>>> json.dumps(s)
'"\\u00e0"'

or a UTF-16 (big-endian)-encoded string:

>>> s.encode("utf-16-be")
'\x00\xe0'

but your original request is not fulfillable.

As an aside, note that u'\u00e0' is identical to u'\xe0', but '\u00e0' doesn't exist:

>>> u'\u00e0'
u'\xe0'

Upvotes: 5

Related Questions