在python中显示西里尔字母符号
假设我在一个变量中有一个俄语内容:在python中显示西里尔字母符号,python,encoding,cyrillic,Python,Encoding,Cyrillic,假设我在一个变量中有一个俄语内容: 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非常接近 中有示例代码 它只涉及unicode类型,但可以很
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
非常接近
中有示例代码
它只涉及unicode类型,但可以很容易地适应utf-8编码的str/字节,如OP
理想情况下,pprint应该保持不变,即格式化/打印的PDO是有效的Python表达式。链接代码也可以被黑客攻击以保持这种不变量
您可以使用monkey pathpprint
模块来维护此不变量:
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"€", "€"]
Python容器使用
repr()
来表示包含的值;输出仅用于调试目的。您是否必须为列表对象生成带有引号和方括号的输出?@qarma:但这不是unicode值。这是一个字节字符串。@MartijnPieters详细信息!我说的是OP想要什么,不是他要什么:P@qarma:您需要在文章中解决这个问题,因为您链接到的解决方案只适用于unicode
对象。@zjor您的目标是什么版本的Python?
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"€", "€"]