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

标签 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'))

如何使用 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/

相关文章:

regex - 如何使用 swift 正则表达式捕获 unicode 字符

python - 通过 Tk 小部件/窗口路径名访问小部件

python - 使用 Spearman 相关性和 Sklearn KNN 进行模式匹配

python - 在列表列表中查找关联值

html - 我们如何在移动版 Safari 中更改 dingbat unicode 字符的颜色和大小? (html 实体)

mysql - ä 存储为 ä 值在数据库中编码

python - 根据使用多列的条件聚合 Pandas DataFrame?

python - 未能通过 GradientDescentOptimizer 找到零权重

python - 如何对经度和纬度进行分箱并绘制分箱的密度?

python - 尝试在循环下打印多个变量