Python 2.7中的中文字符串编码问题

版权声明: https://blog.csdn.net/Geroge_lmx/article/details/83896717

最近在利用python匹配数据库中文字符串中的某些关键字时,遇到了字符串编码问题:

    'ascii' codec can't encode characters...'

下面就来讨论一下此类问题的解决方法,先从一些基本操作入手:

1. Linux Shell查看文件编码类型:

     # vim 文件  打开文件后
     # :set fileencoding

备注:windows下可以使用spyder,notepad++等工具查看文件编码方式

2. 查看Oracle数据库字符集编码:

     select * from nls_database_parameters where parameter ='NLS_CHARACTERSET';   #结果ZHS16GBK

3.方案:

     1)中文字符串的编码默认情况下 = 代码文件的编码方式:

           decode("文件编码")  ----> 再encode("另一种编码")成指定的编码 ----> 使用指定编码解码decode("编码")

     2)如果中文字符串在定义时采用 u"中文字符串" 格式,则对象被指定为unicode类型,编码格式与文件的编码方式无关:

           encode("另一种编码")成指定的编码 ----> 使用指定编码解码decode("编码")

# -*- coding: utf-8 -*-

#s=u"厉害了,我的国"
s="厉害了,我的国" 
 
if isinstance(s, unicode): 
    #s=u"中文" 
    print s.encode('gb2312').decode('gb2312')
else: 
    #s="中文" 
    print s.decode('utf-8').encode('gb2312').decode('gb2312')

4.备注:

1)python2.7中decode()和encode()默认使用"ascii"解码/编码

2)可以使用sys.getdefaultencoding()函数查看默认编码方式

3)字符串在python内部表示为unicode码,因此在编解码转换时通常将unicode作为中间状态,先decode()为unicode,再进行编码,最后解码为自己期望的字符串编码。

猜你喜欢

转载自blog.csdn.net/Geroge_lmx/article/details/83896717