python2中文编码问题

Created at 2020-10-19 Updated at 2021-12-12 Category python Tag python

Python2 有两种字符串类型: strunicode

strunicode 使用decode

unicodestr 使用 encode

a = '中秋' # str
b = u'中秋' # unicode

print a.decode('utf-8')
print b.encode('utf-8')

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)的错误原因是使用了错误的字符集来 encode / decode。

  • 在同时包含 str 与 unicode 的运算时,python 一律把 str 都转换成 unicode 再运算,运算结果也是 unicode

  • 由于 Python 事先并不知道 str 的编码,它只能使用 sys.getdefaultencoding() 编码去 decode,sys.getdefaultencoding() 的值默认是 ascii。 如果需要转换的 str 有中文,一定会出现错误。

  • 可以修改默认编码,或者遇到中文都使用u'中文'

    reload(sys)                      # reload 才能调用 setdefaultencoding 方法  
    sys.setdefaultencoding('utf-8')  # 设置 'utf-8'  
print (unicode("请输入销售额", encoding="utf-8"))

Table of Content

Site by Cellophane using Hexo & Random

Hide