【问题标题】:Displaying cyrillic symbols in python在python中显示西里尔符号
【发布时间】:2014-06-01 15:40:20
【问题描述】:

假设我在变量中有一个俄语内容:

msg = '<some russian text here>'
print msg 

给了我正确的价值,但是

print [msg]

给我这个:

['\xd0\x9f\xd0\xa4 "\xd0\x9a\xd0\xa2\xd0\x9f-\xd0\xa3\xd1\x80\xd0\xb0\xd0\xbb" (\xd0\x97\xd0\x90\xd0\x9e)']

如何在列表中保留西里尔符号?

【问题讨论】:

  • Python 容器使用repr() 来表示包含的值;输出仅用于调试目的。您必须使用' 引号和方括号生成列表对象的输出吗?
  • @qarma:但这不是 unicode 值。它是一个字节字符串
  • @MartijnPieters 详情!我说的是 OP 想要什么,而不是他要求什么:P
  • @qarma:不过,您需要在帖子中解决该问题,因为您链接到的解决方案仅适用于 unicode 对象。
  • @zjor 你的目标是什么版本的 Python?

标签: python encoding cyrillic


【解决方案1】:

您不能直接这样做,但您可以与pprint 非常接近。

https://stackoverflow.com/a/10883893/705086中有示例代码

它仅涵盖 unicode 类型,但可以像 OP 一样轻松适应 utf-8 编码的 str/bytes。

理想情况下,pprint 应该保持格式化/打印的 PDO 是一个有效的 Python 表达式的不变性。链接代码也可以被黑客攻击以保持这种不变性。

你可以通过monkey-path pprint模块来维护这个不变量:

import functools, pprint

def escape(s):
    lead = ""
    if isinstance(s, unicode):
        s = s.encode("utf-8")
        lead = "u"
    return "%s\"%s\"" % (lead, s.replace("\\", "\\\\").replace("\"", "\\\""))

def patched(f):
    if hasattr(f, "_already_patched"):
        return f

    @functools.wraps(f)
    def sub(object, *args, **kwargs):
        try:
            if isinstance(object, basestring):
                return escape(object), True, False
        except Exception:
            pass
        return f(object, *args, **kwargs)

    sub._already_patched = True
    return sub

pprint._safe_repr = patched(pprint._safe_repr)

pprint.pprint([u"\N{EURO SIGN}", u"\N{EURO SIGN}".encode("utf-8")])
[u"€", "€"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多