Home > Backend Development > Python Tutorial > Detailed explanation of the use of ascii and Unicode in python3

Detailed explanation of the use of ascii and Unicode in python3

高洛峰
Release: 2017-03-26 18:39:20
Original
1688 people have browsed it

This article mainly explains in detail the relevant information about the use of ascii and Unicode in python3. Friends in need can refer to it

# Auther: Aaron Fan
'''
ASCII:不支持中文,1个英文占1个字节
Unicode(万国码,支持所有国家的文字显示):支持中文,但是每个英文和中文都占2个字节
UTF-8(是一种针对Unicode的可变长度字符编码,又称万国码。):
   英文依然按照ASCII的方式占1个字节,所有的中文字符统一是3个字节
   Unicode里面支持各个国家的编码转换,比如当中国的gbk格式的软件在日本打开出现乱码的时候,
   必须把gbk转成Unicode编码后才可以正常显示。
GBK:全称《汉字内码扩展规范》(GBK即“国标”、“扩展”汉语拼音的第一个字母,
   英文名称:Chinese Internal Code Specification)
'''
'''
1、先转成Unicode
2、再转换成gbk
概括就是:先编码,后解码
'''

#示例:
'''
gbk_file是一个gbk编码的文件

需求:
把gbk_file转换成一个utf8编码的新文件,新文件名为:gbk_to_utf8_file
'''

#python3一行命令搞定的方法
#把gbk文件转换成utf8文件,源文件gbk_file,目标文件utf8file:
open('utf8file','w+',encoding='utf-8').write(open('gbk_file','r',encoding='gbk').read())
#把utf8文件转换成gbk文件,源文件utf8file,目标文件gbk_file:
open('gbk_file','w+',encoding='gbk').write(open('utf8file','r',encoding='utf-8').read())

#python2上的实现方式:
#gbk文件转换成utf8文件,源文件newfile,目标文件utf8file:
pen('utf8file','w+').write(open('newfile','r').read().decode('gbk').encode('utf-8'))
Copy after login

The above is the detailed content of Detailed explanation of the use of ascii and Unicode in python3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template