Python 基础速查表

来源:互联网 发布:c语言计算时间间隔 编辑:程序博客网 时间:2024/06/13 12:45

数据类型

Integer

-256, 15

Float

-253.23, 1.253e-10

String

"­Hel­lo", 'Goodbye', "­"­"­Mul­til­ine­"­"­"

Boolean

True, False

List

value, ... ]

Tuple

value, ... )

Dictionary

keyvalue, ... }

Set

valuevalue, ... }

语句

If 语句

if expre­ssion: ­ ­sta­tementselif expre­ssion: ­ ­sta­tementselse: ­ ­sta­tements


While Loop

while expre­ssion: ­ ­sta­tements


For Loop

for var in colle­ction: ­ ­sta­tements


Counting For Loop

for i in range(­st­art, end [, step]): ­ ­sta­tements(start is included; end is not)

 

算术运算符

x + y

x - y

x * y

x / y

x % y

取模

x ** y

xy

Assignment shortcuts: x op= y
示例: x += 1 递增 x

比较运算符

x< y

小于

x <= y

小于等于

x > y

大于

x >= y

大于等于

x == y

相等

x != y

不等

布尔运算符

not x

x and y

x or y

转换函数

int(e­xpr)

expr转成整型

float(­expr)

expr转成浮点型

str(e­xpr)

expr转成字符串

chr(num)

ASCII char num

String / List / Tuple 操作

len(s)

s长度

s[i]

s中的第i个值 (从0开始)

s[s­tart :end]

从开始(包括)到结束(不包括)的片段

x in s

如果x包含在s中则为true

x not ins

如果x不包含在s中,则为true

s + t

把s与t的相连接

s * n

s复制n

sorted­(s)

对s进行排序

s.in­dex­(i­tem)

item在s中的位置

更多字符串操作

s.lo­wer()

转成小写

s.re­pla­ce(­old,new)

把 s 中的 old 替换成 new

s.split( delim )

由delim分隔的子字符串列表

s.st­rip()

用于移除字符串头尾的空格

s.up­per()

转成大写

更多 http:/­/do­cs.p­yt­hon.or­g/l­ibr­ary­/st­dty­pes.ht­ml#­str­ing­-me­thods

Mutating List 操作

del lst[i]

删除列表中的第i个项目

lst.a­pp­end­(e)

将e追加到lst中

lst.i­ns­ert­(ie)

在第i个项目前插入e

lst.s­ort()

排序lst

字典操作

len(d)

d中的项目数

del d[key]

根据key从d中删除

key in d

如果d包含key,则为true

d.keys()

返回d中的key列表

函数定义

def name­(a­rg1, arg2, ...): ­ ­st­ate­ments ­ ­return expr

 

Enviro­nment

sys.argv

命令行参数列表(argv [0]可执行)

os.environ

环境变量字典

os.curdir

当前目录路径

import sys; print(­sys.ar­gv)­ ­ ­ ­ orfrom sys import argv; print(­argv)

 

实用的函数

exit( code )

使用exitcode终止程序

raw_in­put­("p­rom­pt­")

从stdin打印 prompt 和 readline()

在Python 3使用input(­"­pr­omp­t")

字符串格式化

"­Hello, {0} {1}".fo­rma­t("a­be", "­jon­es")Hello, abe jones"­Hello, {fn} {ln}".f­orm­at(­fn=­"­abe­", ln="­jon­es")Hello, abe jones"You owe me ${0:,.2­f}­".fo­rma­t(2­534­22.3)You owe me $253,4­22.30now = dateti­me.n­ow()'{:%Y-­%m-%d %H:%M:­%S}­'.f­orm­at(now)201612-16 15:04:33

 

代码片段

循环序列
for index, value in enumer­ate­(seq):
 ­ ­pri­nt(­"{} : {}".f­or­mat­(index, value))

循环字典
for key in sorted­(dict):
 ­ ­pri­nt(­dic­t[key])

读取一个文件
with open("f­ile­nam­e", "­r") as f:
 ­ for line in f:
 ­ ­ ­ line = line.r­str­ip(­"­\n") # Strip newline
 ­ ­ ­ ­pri­nt(­line)