1. 程式人生 > >02-python學習之路

02-python學習之路

轉換 top cal 函數 tle split() sqrt exce type

python關鍵字

import keyword

print(keyword.kwlist)

[‘False‘, ‘None‘, ‘True‘, ‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘nonlocal‘, ‘not‘, ‘or‘, ‘pass‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]

變量類型

  type(變量名 )

  isintance(變量名,類型)

python基本數學函數

max() 求最大值

min() 求最小值

pow() 求n次方 pow(a, b)

round(float) 四舍五入 round(float, n)

import math

help(math) 查看math庫的基本方法

例子:

math.ceil(float) 向上取整

math.floor(float) 向下取整

math.modf(float) 返回整數部分與小數部分

math.sqrt(n) 開方

隨機數

import random

基本例子:

random.choice(seq) # 從序列中隨機選取一個元素 seq: list tuple string

random.randint(1, 10) # 生成1到10的一個整數型隨機數

random.random() # 生成0到1之間的隨機浮點數 [0, 1)

random.randrange(a, b, n) # 生成從a到b的間隔為n的隨機整數 random.randrange([start,] stop[, step])

readom.shuffle(seq) # 將序列seq的元素順序打亂 sep: list tuple

random.uniform(float1, float2) # 生成 float1 到 float2 之間的隨機浮點數,區間可以不是整數 [f1, f2]

python 中 / 與 // 的區別

" / " 表示浮點數除法,返回浮點結果

" // " 表示整數除法,返回一個不大於結果的一個最大整數

格式化輸出

占位符

%d

%s

%f

轉義字符

\

\n

\t

\r

\\

python 用r‘ ‘ 默認內部的字符串不轉義

r‘ \\\\t\n\\‘ windows下路徑 re

字符串基本方法

str = eval(str) 將字符串str當成有效的表達式來求值並返回結果

len(str) 返回字符串的長度

str.upper() 將字符串的小寫字母轉換為大寫字母

str.lower() 將字符串的大寫字母轉換為小寫字母

str.swapcase() 翻轉字符串的大小寫

str.capitalize() 將字符串首字母大寫, 其它小寫

str.title() 每個單詞的首字母大寫

str.center(width, fillchar) 返回一個指定寬度的居中字符串, fillchar為填充的字符串

str.ljust(width, fillchar)

str.replace()

str.strip()

str.split()

02-python學習之路