栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

代码实例讲解python3的编码问题

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

代码实例讲解python3的编码问题

python3的编码问题。

打开python开发工具IDLE,新建‘codetest.py'文件,并写代码如下:

import sys

print (sys.getdefaultencoding())

F5运行程序,打印出系统默认编码方式

将字符串从str格式编码程bytes格式,修改代码如下:

import sys

print (sys.getdefaultencoding())

s = '你好'

print (type(s))

b = s.encode('utf-8')

print (type(b))

print (b)

 

其中b = s.encode('utf-8') 等同于b = s.encode() ,因为系统默认编码方式就是utf-8

F5运行程序,打印出内容如下,中文必须用utf-8编码,因为ascii码表示不了所有汉字,这里暂时不介绍gbk编码,现在用得很少了,utf-8使用3个字节表示一个汉字,ascii使用一个字节表示一个英文字母或字符。

解码就是从bytes变回str的过程,修改代码如下:

import sys

 

print (sys.getdefaultencoding())

s = '你好'

print (type(s))

b = s.encode('utf-8')

print (type(b))

print (b)

se = b.decode('utf-8')

print (se)

print (type(se))

 

F5运行程序,打印内容如下图,bytes转回str

utf-8编码兼容ascii,当既有中文又有英文时使用encode('utf-8'),英文还是占一个字节,中国三个字节,另外当py文件注释有中文时,需要在头部添加

#coding:utf-8

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/25463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号