sublime txt 3 中 Python3 代码含中文 运行错误的解决方法(mac环境)UnicodeEncodeError: ‘ascii’ codec can’t encode charact

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28616789/article/details/79190946

今天在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')

这样,程序就能正确运行了。
如图:
这里写图片描述

  • 其实,除此之外,还可以直接将源代码放在电脑终端运行,也可以正确运行,如图是运行效果:
    这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_28616789/article/details/79190946
今日推荐