编码的问题
中文版 Windows 终端是默认GBK编码格式,python2默认为ASCII编码,虽然我们注释了需要用UTF-8,但是通过命令行运行的文件如果print中文内容还是会出现乱码。
Unicode, UFT-8, GBK 分别是三种不同的编码,Unicode在转为UTF-8或GBK时需要经过编码的过程,而UTF-8或GBK变为Unicode则需要经过解码。因此UTF-8和GBK的转化就需要经过一个解码和编码的过程。所以即使我们在py文档里注明了使用utf-8编码,在默认使用gbk的终端里,出现的中文是会乱码的。
因此,在中文windows终端运行python2文件,我们需要对内容先解码再编码,如下: 这样以后我们在终端看到的就可以是正确的中文字了 (使用decode()和encode()先将内容从utf-8解码,然后再编码为gbk显示)
在python3里,python编码做了优化,自身转化utf-8, unicode, gbk, 移除了python的utf-8类型
**Q: python3里的文本都可以正常显示在终端里,在使用python2.7的Ubuntu里,直接print的中文正常显示,而decode再encode的中文字符反而乱码了。TBD
naomi@ubuntu:~/Desktop$ cat test #!/usr/bin/python # -*- coding:utf-8 -*- val = '中文咯' val_unicode = val.decode('utf-8') val_gbk = val_unicode.encode('gbk') print(val_gbk) print('这也是中文')
运算符
'//' 取整
使用PyCharm IDE来创建Python项目文件,设置默认模板(Files - Settings - Editor - File and Code Template 在python文件里添加 #!/usr/bin/python 设置即可)
python2里的'/'除法不显示小数的问题,可以通过from __future__ import division 来得到小数结果
PyCharm里p2和p3的切换:files - settings - 目标project - interpreter 选择p3即可
成员运算符
in
not in
str1 = 'big brother is watching you' text1 = 'big' in str1 text2 = ' ' in str1 text3 = 'isw' in str1 text4 = 'ther' in str1 print(text1) # True print(text2) # True print(text3) # False print(text4) # True list1 = ['big', 'brother', '1', 'watching', ' you'] text5 = 'big' in list1 text6 = ' ' in list1 text7 = 'ther' not in list1 print(text5) # True print(text6) # False print(text7) # True