【发布时间】:2012-01-04 13:13:46
【问题描述】:
>>> s = 'auszuschließen'
>>> print(s.encode('ascii', errors='xmlcharrefreplace'))
b'auszuschließen'
>>> print(str(s.encode('ascii', errors='xmlcharrefreplace'), 'ascii'))
auszuschließen
有没有更漂亮的方法来打印没有b'' 的任何字符串?
编辑:
我只是想从 Python 打印转义字符,我唯一的抱怨是当我这样做时 Python 添加了“b''”。
如果我想在像 Windows 7 这样的哑终端中看到实际角色,那么我会得到这个:
Traceback (most recent call last):
File "Mailgen.py", line 378, in <module>
marked_copy = mark_markup(language_column, item_row)
File "Mailgen.py", line 210, in mark_markup
print("TP: %r" % "".join(to_print))
File "c:\python32\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2026' in position 29: character maps to <undefined>
【问题讨论】:
-
你为什么不直接使用
print(s)?为什么需要编码为ascii? -
因为我不认为我的终端支持我的代码处理的每一个奇怪的字符。
-
print(str(s.encode('ascii', errors='ignore'), 'ascii')) 会更漂亮,无论如何。
-
我已经更新了我的答案。虽然这回答了你的问题,但它有一种实际上解决了错误问题的感觉。我脑海中浮现的问题是,为什么您想要“漂亮”输出本质上是调试信息(字符串中的 Unicode 字符)。这个日志是应该提供给另一个程序的实际程序用户界面或标准输出输出,还是......?
-
您也可以设置环境变量PYTHONIOENCODING=cp437:backslashreplace,然后使用
print(s)。我没有在答案中提到它,因为python might crash if you set it incorrectly.
标签: python python-3.x