如何在python 3中使用raw_unicode_escape编码打印字符串?

sor*_*rin 2 python unicode python-3.x

以下代码在Python 3.x中失败,TypeError: must be str, not bytes因为现在只encode()返回bytesprint()期望str.

#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))
Run Code Online (Sandbox Code Playgroud)

如何使用print()?打印Unicode字符串转义表示?我正在寻找一种适用于Python 2.6或更高版本的解决方案,包括3.x.

更新

下面的行将与3.x一起使用,但它不适用于2.6,生成 AttributeError: 'file' object has no attribute 'buffer'

sys.stdout.buffer.write(str2.encode('raw_unicode_escape'))
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 5

我只是用:

print(str2.encode('raw_unicode_escape').decode('ascii'))
Run Code Online (Sandbox Code Playgroud)

如果你想在Python 3和Python 2.6中使用相同的代码(否则你可以repr在2.6和asciiPython 3中使用,但那不是真的"相同";-).