Pulpcode

捕获,搅碎,拼接,吞咽

0%

python技巧

如果你的文件中有不是ASCII的字符编码,那么请使用如下命令:

# -*- coding: utf-8 -*-

如果有脚本文件运行,那么在运行行前

#!/usr/bin/python
# -*- coding: utf-8 -*-

实际上python只检查#, coding 和编码字符串,其他的字符都是为了美观加上的。


这样的除法会非常精准

from __future__ import division

这样的写法,可以省略打开文件的trycatch

from __future__ import with_statement

with open("file_name") as abc:

将当前目录下的文件,文件夹添加到路径下。

path = os.path.join(os.path.dirname(__file__), 'index.html')

在tornado中常常有这样的写法:

"static_path": os.path.join(os.path.dirname(__file__),"static")
"template_path": os.path.join(os.path.dirname(__file__), "templates")

如下语句会将 “ a b c d “,统一为一个长度的标准间距: “a b c d”。
甚至将多行合并到单行,这可以被称为是惯用法(或者说技巧)。

' '.join(s.split())

返回一个对象可调用的方法列表

methodlist = [method for method in dir(object) if callable(getattr(object,method))]

sys.path作为python的模块搜索路径。
如果你有自己的模块目录,可以使用此方法来加入。
sys.path.append('my/new/path')


dive into python中的一个程序

__author__ = "Aiqi Liu (liuaiqi627@gmail.com)"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2013/10/17 09:47:04 $"
__copyright__ = "Copyright (c) 2013 Aiqi Liu"
__license__ = "Python"

def buildConnectionString(params):
    """Build a conection string from a dictionary

    Returns string.
    """
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim", \
                "database":"master", \
                "uid":"sa", \
                "pwd":"secret"
                }
    print buildConnectionstring(myParams)
  1. dict 字典不能直接迭代,需要params.items()。
  2. 三个引号之间的内容作为此函数的doc。
  3. join 用来链接一个列表中的内容。
  4. 引伸一下,os.path.join 是一个用来将目录链接成完整路径的函数。