The following code with fail in Python 3.x with TypeError: must be str, not bytes because now encode() returns bytes and print() expects only str.
#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))
How can you print a Unicode string escaped representation using print()? I’m looking for a solution that will work with Python 2.6 or newer, including 3.x
Update
Below line will work with 3.x but it will not work with 2.6, generating AttributeError: 'file' object has no attribute 'buffer'
sys.stdout.buffer.write(str2.encode('raw_unicode_escape'))
I’d just use:
if you want identical code in Python 3 and Python 2.6 (otherwise you could use
reprin 2.6 andasciiin Python 3, but that’s not really “identical”;-).