以下代码在 Python 3.x 中失败,并出现 TypeError: Must be str, not bytes
因为现在 encode()
返回 bytes
而 print()
只需要 str
。
#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))
如何使用 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'))
最佳答案
我只想使用:
print(str2.encode('raw_unicode_escape').decode('ascii'))
如果你想在Python 3和Python 2.6中使用相同的代码(否则你可以在2.6中使用repr
,在Python 3中使用ascii
,但这并不是真正的“相同”; -)。
关于python - 如何在 python 3 中使用 raw_unicode_escape 编码打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038618/