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

yipeiwu_com6年前Python基础

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

相关文章

python 捕获 shell/bash 脚本的输出结果实例

#!/usr/bin/python ## get subprocess module import subprocess   ## call date command ##...

Python标准库os.path包、glob包使用实例

os.path包 os.path包主要用于处理字符串路径,比如'/home/zikong/doc/file.doc',提取出有用的信息。 复制代码 代码如下: import os.pat...

python创建子类的方法分析

本文实例讲述了python创建子类的方法。分享给大家供大家参考,具体如下: 如果你的类没有从任何祖先类派生,可以使用object作为父类的名字。经典类的声明唯一不同之处在于其没有从祖先类...

Django框架下在URLconf中指定视图缓存的方法

将视图与缓存系统进行了耦合,从几个方面来说并不理想。 例如,你可能想在某个无缓存的站点中重用该视图函数,或者你可能想将该视图发布给那些不想通过缓存使用它们的人。 解决这些问题的方法是在...

Python Pillow.Image 图像保存和参数选择方式

保存时代码如下: figure_corp = figure.crop( (32*rate/2, 32*rate/2, 32-32*rate/2, 32-32*rate/2)) fig...