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

yipeiwu_com5年前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使用reportlab实现图片转换成pdf的方法

本文实例讲述了python使用reportlab实现图片转换成pdf的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python import os...

Python中list列表的一些进阶使用方法介绍

判断一个 list 是否为空 传统的方式: if len(mylist): # Do something with my list else: # The list is e...

Python中str is not callable问题详解及解决办法

Python中str is not callable问题详解及解决办法 问题提出:    在Python的代码,在运行过程中,碰到了一个错误信息:  &nb...

pytorch神经网络之卷积层与全连接层参数的设置方法

当使用pytorch写网络结构的时候,本人发现在卷积层与第一个全连接层的全连接层的input_features不知道该写多少?一开始本人的做法是对着pytorch官网的公式推,但是总是算...

Python分支语句与循环语句应用实例分析

本文实例讲述了Python分支语句与循环语句应用。分享给大家供大家参考,具体如下: 一、分支语句 1、if else语句 语法: if 条件判断: 执行的语句块1 else :...