Python中中文字符串怎么处理?

图片[1]-Python中中文字符串怎么处理?-uusu优素-乐高,模型,3d打印,编程

如果处理的字符串中出现中文表示的字符,要想不出错,就得转成unicode编码了。具体的方法有:

1、decode(),将其他边编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码;

2、encode(),将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码;

3、unicode(),同decode(),将其他编码的字符串转换成unicode编码,如unicode(str3, 'gb2312'),表示将gb2312编码的字符串str3转换成unicode编码。

转码的时候一定要先搞明白字符串str是什么编码,然后decode成unicode,最后再encode成其他编码。

另外,对一个unicode编码的字符串在进行解码会出错,所以在编码未知的情况下要先判断其编码方式是否为unicode,可以用isinstance(str, unicode)。

不仅是中文,以后处理含非ascii编码的字符串时,都可以遵循以下步骤:

1、确定源字符的编码格式,假设是utf8;

2、使用unicode()或decode()转换成unicode编码,如str1.decode('utf8'),或者unicode(str1, 'utf8');

原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容