2024-04-19 10:36:05 发布
网友
假设我在变量中有一个俄语内容:
msg = '<some russian text here>' 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)']
如何在列表中保留西里尔文符号?在
您不能直接这样做,但是您可以非常接近pprint。在
pprint
https://stackoverflow.com/a/10883893/705086中有示例代码
它只覆盖unicode类型,但可以很容易地适应utf-8编码的str/bytes,就像在OP中一样
理想情况下,Python应该保持PDO/pprint格式不变。链接代码也可以通过黑客攻击来保持这种不变性。在
您可以使用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"€", "€"]
您不能直接这样做,但是您可以非常接近
pprint
。在https://stackoverflow.com/a/10883893/705086中有示例代码
它只覆盖unicode类型,但可以很容易地适应utf-8编码的str/bytes,就像在OP中一样
理想情况下,Python应该保持PDO/pprint格式不变。链接代码也可以通过黑客攻击来保持这种不变性。在
您可以使用monkey path
pprint
模块来维护此不变量:相关问题 更多 >
编程相关推荐