网站优化工作室/友情链接代码美化
python2
字符串
python2的字符串有两种:str、unicode,默认的是str,在内存中存储的是代码文件编码的原始字节串。如果需要转码,无论代码文件使用的编码是gbk还是utf-8,都需要先把str对象.decode('代码文件编码')转换为unicode,然后在unicode对象.encode('目标编码')。
str -> decode -> unicode -> encode -> str
open函数
python2的open函数于python3的函数不同,函数签名如下:
open(name[, mode[, buffering]])
python2编码示例:
py2gbk.py
使用python版本:python2 代码文件编码:gbk
#!/usr
#encoding: gbk
html = '我是中文'
f = open('py2gbk_utf.html', 'w')
f.write(html.decode('gbk'))
f.close()
f = open('py2gbk_gbk.html', 'w')
f.write(html)
f.close()
py2utf.py
使用python版本:python2 代码文件编码:utf-8
#encoding: utf-8
html = '我是中文'
f = open('py2utf_utf.html', 'w')
f.write(html)
f.close()
f = open('py2utf_gbk.html', 'w')
f.write(html.decode('utf-8').encode('gbk'))
f.close()
codecs模块
import codecs
codecs.open('utfdata', 'w', encoding='utf-8').write(S) # 写入
codecs.open('utfdata', 'r', encoding='utf-8').read() # 读取
python3
字符串
python3的字符串只有一种:str,支持unicode编码,无论代码文件使用的任何编码均转换为unicode编码存储在内存中。如果需要转码,str对象.encode('目标编码')转换为bytes。
str -> encode -> bytes
byte数组
python3中还有byte数组类型:bytes,bytearray。如果需要转换为字符串,bytes对象.decode('bytes对象的编码')转换为str。
bytes -> decode -> str
open函数
python3的open函数更加人性化有编码参数。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
其他
python3编码示例:
py3gbk.py
使用python版本:python3 代码文件编码:gbk
#encoding: gbk
html = '我是中文'
f = open('py3gbk_utf.html', 'wb')
f.write(html.encode('utf-8'))
f.close()
f = open('py3gbk_gbk.html', 'wb')
f.write(html.encode('gbk'))
f.close()
py3utf.py
使用python版本:python3 代码文件编码:utf-8
#encoding: utf-8
html = '我是中文'
f = open('py3utf_utf.html', 'w', encoding='utf-8')
f.write(html)
f.close()
f = open('py3utf_gbk.html', 'w', encoding='gbk')
f.write(html)
f.close()
查看编码
[root@localhost ~]# echo 中文 | xxd
0000000: e4b8 ade6 9687 0a .......
[root@localhost ~]# echo 中文 | iconv -f utf-8 -t gbk | xxd
0000000: d6d0 cec4 0a .....