3

I have a string my_string which holds a newline character. So, if printed it will introduce a new line.

Initially, I do my_string.encode('unicode_escape').decode("utf-8")

where print(my_string.encode('unicode_escape').decode("utf-8")) gives \n

and print (repr(my_string)) gives '\\n'.

Then, want I want to do is convert it back to its original state so that it prints the newline, i.e. my_string not to display the newline character \n or \\n but simply introduce a new line.

I searched for encode and decode but could not figure out how to do it.

1 Answer 1

10

Since you're first encoding with unicode_escape, then decoding with utf-8, the inverse operation would be the inverse of the individual operations, in reverse order:

>>> x = '\n'
>>> y = x.encode('unicode_escape').decode('utf-8')
>>> y.encode('utf-8').decode('unicode_escape')
'\n'

(The socks/shoes principle: You first put on your socks and then your shoes; to undo that you first remove your shoes and then your socks.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.