【发布时间】:2017-08-24 10:14:53
【问题描述】:
考虑以下终端命令行
python3 -c 'print("hören")'
在大多数终端中,这会打印“hören”(德语为“听到”),在 一些 终端中会出现错误
UnicodeEncodeError: 'ascii' codec can't encode character '\xf6'
in position 1: ordinal not in range(128)
在我的 Python3 程序中,我不希望仅仅打印出一些 可以 引发这样的异常的内容,而是希望输出不会引发异常的字符。
所以我的问题是:如何在忽略不可编码字符的情况下输出 Python3(unicode)字符串?
一些注意事项
到目前为止我所做的尝试
我尝试使用
sys.stdout.write而不是print,但仍然会出现编码问题。-
我尝试通过 byes 对字符串进行编码
bytes=line.encode('utf-8')这不会在打印时引发异常,但即使在有能力的终端中,非 ascii 字符也会被它们的代码点编号替换。
-
我尝试使用带有
'ignore'参数的decode方法:bytes=line.encode('utf-8') decoded=bytes.decode('utf-8', 'ignore') print(decoded)但问题不在于字符串中的解码,而在于 in 中的 print 函数。
这里有些终端似乎不能支持所有字符
macOS 上 Emacs 中的 bash shell。
-
通过
do shell script在 Applescript 中接收“打印”字符串,例如:set txt to do shell script "/usr/local/bin/python3 -c \"print('hören')\" "
更新:这些终端都从locale.getpreferredencoding()返回值US-ASCII。
【问题讨论】:
标签: python-3.x unicode character-encoding