今天在sublime txt 3 中运行下面这段Python3 的代码:
words = {
'tuple': '元祖',
'list': '列表',
'readability': '可读性',
'practicality': '实用性',
'dense': '稠密的',
}
for word_key in list(words):
print(word_key + ": " + words[word_key])
出现了以下错误:
Traceback (most recent call last):
File “/Users/tiramisu/python_work/6/words_table.py”, line 14, in
print(word_key + “: ” + words[word_key])
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 7-8: ordinal not in range(128)
在网上找了好多种办法,对于这个问题都解决不了。估计那些方法都是用来解决Python2的吧。
- 最后,成功找到了一个解决方法,在代码的最前面加入这三行代码:
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
这样,程序就能正确运行了。
如图:
- 其实,除此之外,还可以直接将源代码放在电脑终端运行,也可以正确运行,如图是运行效果: