How to encode a Python 3 string using \ u escape code?

In Python 3, suppose I have

>>> thai_string = 'สีเ'

Use encodegives

>>> thai_string.encode('utf-8')
b'\xe0\xb8\xaa\xe0\xb8\xb5'

My question is: how can I get encode()to return a sequence bytesusing \uinstead \x? And how can I return decodeto type Python 3 str?

I tried using the built in asciiwhich gives

>>> ascii(thai_string)
"'\\u0e2a\\u0e35'"

But this does not seem to be correct, since I cannot decode it to receive thai_string.

The Python documentation tells me that

  • \xhhdisplays a character with a hexadecimal value hh, and
  • \uxxxx displays a character with a hexadecimal value xxxx

, \u , , . , ?

+4
1

unicode_escape:

>>> thai_string.encode('unicode_escape')
b'\\u0e2a\\u0e35\\u0e40'

, encode() () unicode_escape :

, Python

+4

All Articles