I have a string in python 3 that has several unicode representations in it, for example:
t = 'R\\u00f3is\\u00edn'
and I want to convert t so that it has the proper representation when I print it, ie:
>>> print(t)
Róisín
However I just get the original string back. I’ve tried re.sub and some others, but I can’t seem to find a way that will change these characters without having to iterate over each one.
What would be the easiest way to do so?
You want to use the built-in codec
unicode_escape.If
tis already abytes(an 8-bit string), it’s as simple as this:If
thas already been decoded to Unicode, you can to encode it back to abytesand thendecodeit this way. If you’re sure that all of your Unicode characters have been escaped, it actually doesn’t matter what codec you use to do the encode. Otherwise, you could try to get your original byte string back, but it’s simpler, and probably safer, to just force any non-encoded characters to get encoded, and then they’ll get decoded along with the already-encoded ones:In case you want to know how to do this kind of thing with regular expressions in the future, note that
sublets you pass a function instead of a pattern for therepl. And you can convert any hex string into an integer by callingint(hexstring, 16), and any integer into the corresponding Unicode character withchr(note that this is the one bit that’s different in Python 2—you needunichrinstead). So:Or, making it a bit more clear:
The
unicode_escapecodec actually handles\U,\x,\X, octal (\066), and special-character (\n) sequences as well as just\u, and it implements the proper rules for reading only the appropriate max number of digits (4 for\u, 8 for\U, etc., sor'\\u22222'decodes to'∢2'rather than''), and probably more things I haven’t thought of. But this should give you the idea.