Python 基礎速查表

2021-08-03 03:42:13 字數 3525 閱讀 6354

資料型別

integer

-256, 15

float

-253.23, 1.253e-10

string

"­hel­lo", 'goodbye', "­"­"­mul­til­ine­"­"­"

boolean

true, false

list

[ value, ... ]

tuple

( value, ... )

dictionary

set

語句if 語句

if expre­ssion:

­ ­sta­tements

elif expre­ssion:

­ ­sta­tements

else:

­ ­sta­tements

while loop

while expre­ssion:

­ ­sta­tements

for loop

for

varin colle­ction:

­ ­sta­tements

counting for loop

for i in range(­st­art, end [, step]):

­ ­sta­tements

(start

is included; end

isnot)

算術運算子

x + y

加x - y

減x * y

乘x / y

除x % y

取模x ** y

xyassignment 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­(i, e)

在第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)­ ­ ­ ­ or

from sys import argv; print(­argv)

實用的函式

exit( code )

使用exitcode終止程式

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

從stdin列印 prompt 和 readline()

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

字串格式化

"­hello,  ".fo­rma­t("a­be", "­jon­es")

hello, abe jones

"­hello, ".f­orm­at(­fn=­"­abe­", ln="­jon­es")

hello, abe jones

"you owe me $­".fo­rma­t(2­534­22.3)

you owe me $253,4­22.30

now = dateti­me.n­ow()

'­'.f­orm­at(now)

2016-­12-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)

pandas基礎命令速查表

import pandas as pd import numpy as np csv pd.read csv fillname df.to csv fillname pd.dataframe np.random.rand 10,5 df.tail n df.shapedf.info df.descr...

markdown語法速查表

markdown 語法速查表 這是 h1 一級標題 這是 h2 二級標題 這是 h6 六級標題 這是 h6 六級標題 這是文字粗體格式 這是文字斜體格式 在文字上新增刪除線 這是文字粗體格式這是文字斜體格式 在文字上新增刪除線 專案1 專案2 專案3 1.專案1 2.專案2 3.專案3 專案1 專案...

vim指令速查表

命令 描述vim filename 開啟或新建檔案,並將游標置於第一行首 vim n filename 開啟檔案,並將游標置於第n行首 vim filename 開啟檔案,並將游標置於最後一行首 vim pattern filename 開啟檔案,並將游標置於第乙個與pattern匹配的串處 vim...