Lunar
Lunar

Reputation: 33

Change string to byte but the format is string

I want to encode string to unicode like

   >>> s = 'Hello, 안녕'
   >>> u = s.encode('raw_unicode_escape')
   b'Hello, \\uc548\\ub155'
   >>> doing something
   >>> print(u)
   Hello, \uc548\ub155

I would like to show Unicode itself as string so if I write a file Hello, \uc548\ub155 is showing the same.

Upvotes: 0

Views: 55

Answers (1)

Austin R. Scott
Austin R. Scott

Reputation: 193

I'm not 100% sure what you need, so here are some examples:

Unicode Direct

>>> s = 'Hello, 안녕'
>>> print(s)
Hello, 안녕

Unicode \u Codes

>>> s = u'Hello, \uc548\ub155'
>>> print(s)
Hello, 안녕

Unicode → ByteString

>>> u = s.encode('raw_unicode_escape')
>>> print(u)
b'Hello, \\uc548\\ub155'

ByteString → Unicode

>>> u = u.decode('unicode_escape')
>>> print(u)
Hello, 안녕

Translator function

>>> def _(unicode_text):
    return unicode_text.encode('unicode_escape')

. . .

>>> s = f'Hello, {_("안녕")}'
>>> print(s)
Hello, b'\\uc548\\ub155'

Upvotes: 2

Related Questions