置顶:Python官方文档,供着。
Python语法不熟,但又经常用到,每次先查比较麻烦,将常用的汇总下。
文档模板
#!/usr/bin/env python # 起始行, 类Unix环境需要,使能够仅输入脚本名字来执行脚本
"this is a test module" # 模块文档(文档字符串),类似于java中文档式注释,module.__doc__访问
import sys # 模块导入
debug = True # 全局变量,尽量用局部变量代替
class FooClass (object) : # 类定义(若有),模块被导入时class语句被执行,类被定义。class.__doc__访问类文档
"Foo class"
pass
def test() : # 函数定义(若有),模块被导入时def语句被执行,函数被定义。function.__doc__访问函数文档
"test function"
foo = FooClass()
if debug :
print 'run test()'
if __name__ == '__main__' : # 主程序,无论被导入还是被直接执行都会运行。__name__指示模块是导入还是直接执行
test()
IO
- raw_input,读取标准输入,类似于C++中的cin
user = raw_input('enter you name:')
print 'hello','world!', # 逗号,不换行,空格连接
print # 换行符
print '%s is a string, %d is a number' % (str,num) # 标准输出
运算
- 算子
不支持 ++、– 操作符
支持 +=、-=、*=等增量赋值方式 - 逻辑运算
and、or、not
布尔值:True、False
比较操作
- is、is not
a is b # 等价于 id(a) == id(b)
- 连接比较
3 < 4 < 5 # 等价于 (3 < 4) and (4 < 5)
string
- 索引([index])、切片([m:n])
str[1:-1]
- 连接(+)、重复(*)
str + ' ' + str
str * 3
- split
words = line.split('\t')
list
- len
len(words)
time, datetime
- strptime, strftime
import time
t = time.strptime('2000-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
timeStr = time.strftime(t, '%Y-%m-%d %H:%M:%S')
import datetime
dt = datetime.datetime.strptime('2000-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
dtStr = datetime.datetime.strftime(dt, '%Y-%m-%d %H:%M:%S')
- 日期计算
import datetime
ss = (dt1 - dt2).seconds
file
- open
file = open('t.txt', 'r')
file = open('t.txt', 'rb') #二进制读
file = open('t.txt', 'w')
file = open('t.txt', 'w+') #追加
- read
allLines = file.readlines()
- write
file.write(line)