Blogger Information
Blog 41
fans 0
comment 1
visits 40054
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Python高效编程技巧实战(10)
yeyiluLAMP
Original
1034 people have browsed it

snipaste20171003_210153.png

python2.x

In [1]: u'你好'
Out[1]: u'\u4f60\u597d'

In [2]: 'jafldsjjaggh'
Out[2]: 'jafldsjjaggh'

编码

In [5]: s.encode('utf8')
Out[5]: '\xe4\xbd\xa0\xe5\xa5\xbd'

In [6]: print '\xe4\xbd\xa0\xe5\xa5\xbd'
你好

In [7]: '\xe4\xbd\xa0\xe5\xa5\xbd'.decode('utf8')
Out[7]: u'\u4f60\u597d'

解码

In [8]: print '\xe4\xbd\xa0\xe5\xa5\xbd'.decode('utf8')
你好


python2.x读取文件

In [10]: f = open('py2.txt','w')

In [11]: f
Out[11]: <open file 'py2.txt', mode 'w' at 0xb69e2c28>

In [12]: s = u'你好'

In [13]: f.write(s.encode('gbk'))

In [14]: cat py2.txt

In [15]: f.close()

In [16]: cat py2.txt
ţº
In [17]: f = open('py2.txt','r')

In [18]: t = f.read()

In [19]: t
Out[19]: '\xc4\xe3\xba\xc3'

In [20]: t.decode('gbk')
Out[20]: u'\u4f60\u597d'

In [21]: print t.decode('gbk')
你好









python3.x
python3省去了在python2.x中手工编码和解码的工作

在python3.x中表示byte
In [8]: b'eajfsdjfjl'
Out[8]: b'eajfsdjfjl'


在python3.x中表示unicode字符串
In [9]: '你好'
Out[9]: '你好'


In [19]: f = open('py3.txt','wt',encoding='utf8')

In [20]: f
Out[20]: <_io.TextIOWrapper name='py3.txt' mode='wt' encoding='utf8'>

In [21]: f.write('我爱编程!')
Out[21]: 5


In [23]: f.close()

In [24]: f = open('py3.txt','rt',encoding='utf8')

In [25]: f.read()
Out[25]: '我爱编程!'

In [26]: s = f.read()

In [27]: s
Out[27]: ''

重置指针到文件头部初始位置
In [28]: f.seek(0)
Out[28]: 0

In [29]: s = f.read()

In [30]: print(s)
我爱编程!


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!