你可能不知道但很有用的python小技巧

python小技巧

  • 1、超长字符串处理

      在写crapy爬虫时发现当网址太长时很难看,发现可以在合适的位置回车分行过长的字符串,

#分割前:
start_url = 'http://mp.blog.csdn.net/mdeditor'
#分割后:
start_url = ['http://mp.blog'
             '.csdn.net/mdeditor’]

  但是这样手动去分割地址,如果地址复杂又长容易出现错误导致爬取网页失败,可以在 view -> active editor -> 勾选 use soft wraps 这样可以到达一定长度后自动换行默认是120,不过可以在pycharmsetting内设置代码的长度。

  • 扩展

既然这里可以这样那么我们在书写字符串的时候可能也会发现长的字符串很难看,又想到c++,c中都有字符串内换行的功能,然后就仿照scrapy爬虫start_url的写法,书写了一个字符串进行处理,事实证明是可以的。

str = (
    'sdsdasf'
    'sdsfsdfsd'
    'esfdg'
)
if __name__ =="__main__":
    print str


运行结果:
D:\Python\venv_space\venv27\Scripts\python2.exe C:/Users/Administrator/Desktop/jiqiao.py
sdsdasfsdsfsdfsdesfdg

Process finished with exit code 0

  • 2、python2.x中的编码不是 unicode ,而在 Python3.x 中取消了字符串字面量的前缀 u,
    • 一般的解决办法
if sys.version < '3':
        exec("chinese = unicode('中国', 'utf-8')")
else:
        exec("chinese = '中国'")
  • Python2.6 中引入了 unicode_literals,可以很方便地写 2.x/3.x 兼容的代码:

#做一下引入即可
from __future__ import unicode_literals 
  • 发现了一篇小技巧文章
    • python小技巧一

你可能感兴趣的:(python)