查看所有Python相關(guān)學(xué)習(xí)筆記
此篇文章用于記錄學(xué)習(xí)過程中接觸到的零散知識(shí)點(diǎn)(包含已歸納到各個(gè)模塊的知識(shí)點(diǎn))待笑。
用于自我查詢--->>備忘錄
-
開方
x**2 > 等于x的平方 x**3 > 等于x的三次方
-
取整
>>>int(3.44) 3 >>> int(3.9) 3
-
四舍五入
round(number,digits)
number,要四舍五入的數(shù),digits是要小數(shù)點(diǎn)后保留的位數(shù)
- 如果 digits 大于 0,則四舍五入到指定的小數(shù)位。
round(13.2222,1) > 13.2
- 如果 digits 等于 0,則四舍五入到最接近的整數(shù)。
round(13.2222,0) > 13.0
- 如果 digits 小于 0,則在小數(shù)點(diǎn)左側(cè)進(jìn)行四舍五入胀溺。
round(13.2222,-1) > 10.0
round(15.2222,-1) > 20.0
round(15.2222,-2) > 0.0
- 如果round函數(shù)只有參數(shù)number,等同于digits 等于 0。
round(13.2222) > 13
- 如果 digits 大于 0,則四舍五入到指定的小數(shù)位。
-
使用方法修改字符串的大小寫
- upper()將所有字母變?yōu)榇髮戄敵?/li>
- lower()將所有字母變?yōu)樾戄敵?/li>
- capitalize() 首字母大寫皆看,其余小寫
- title() 所有單詞首字母大寫仓坞,其余小寫
>>>s = 'hEllo pYthon' >>>print(s.upper()) >>>print(s.lower()) >>>print(s.capitalize()) >>>print(s.title()) HELLO PYTHON hello python Hello python Hello Python
- Python提供了isupper(),islower()腰吟,istitle()方法用來判斷字符串的大小寫
>>>print('A'.isupper()) >>>print('A'.islower()) >>>print('Python Is So Good'.istitle()) >>># print('Dont do that!'.iscapitalize())#錯(cuò)誤无埃,不存在iscapitalize()方法 True False True
-
刪除空白【strip-刪除徙瓶,清除】
- rstrip()刪除末尾的空白(包括\t和\n)
- lstrip()刪除頭部的空白(包括\t和\n)
- strip()刪除字符串兩端的空白(包括\t和\n)
>>>msg=' python ' >>>print('-'+msg+'-')#初始狀態(tài) >>>print('-'+msg.rstrip()+'-')#刪除右側(cè)空格 >>>print('-'+msg.lstrip()+'-')#刪除左側(cè)空格 >>>print('-'+msg.strip()+'-')#刪除兩側(cè)空格 - python - - python- -python - -python-
-
使用方法sort()對(duì)列表進(jìn)行永久排序-按字母排序
#正序 >>>nicks = ['zhangsan','lisi','wangwu','zhaoliu'] >>>print(nicks)#原始狀態(tài) >>>nicks.sort() >>>print(nicks)#排序后的狀態(tài) ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['lisi', 'wangwu', 'zhangsan', 'zhaoliu'] #倒序 >>>nicks = ['zhangsan','lisi','wangwu','zhaoliu'] >>>print(nicks)#原始狀態(tài) >>>nicks.sort(reverse = True) >>>print(nicks)#排序后的狀態(tài) ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
-
使用方法sorted()對(duì)列表進(jìn)行臨時(shí)排序-按字母排序
>>>nicks = ['zhangsan','lisi','wangwu','zhaoliu'] >>>print(nicks)#原始狀態(tài) >>>print(sorted(nicks))#臨時(shí)排序的狀態(tài)(正序) >>>print(sorted(nicks,reverse = True))#臨時(shí)排序的狀態(tài)(倒序) >>>print(nicks)#使用臨時(shí)排序后,nicks的狀態(tài) ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['lisi', 'wangwu', 'zhangsan', 'zhaoliu'] ['zhaoliu', 'zhangsan', 'wangwu', 'lisi'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
-
倒著打印列表嫉称,按元素反轉(zhuǎn)列表排序
>>>nicks = ['zhangsan','lisi','wangwu','zhaoliu'] >>>print(nicks)#原始狀態(tài) >>>nicks.reverse()#倒轉(zhuǎn) >>>print(nicks)#倒轉(zhuǎn)后的狀態(tài) ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'wangwu', 'lisi', 'zhangsan']
-
方法zfill()在數(shù)值字符串前填充0
>>>'12'.zfill(5) '00012' >>>'-3.14'.zfill(7) '-003.14' >>>'3.14159265359'.zfill(5) '3.14159265359'
-
math模塊為浮點(diǎn)運(yùn)算提供了對(duì)底層C函數(shù)庫(kù)的訪問
>>> import math >>> math.cos(math.pi / 4.0) 0.70710678118654757 >>> math.log(1024, 2) 10.0
-
random提供了生成隨機(jī)數(shù)的工具
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4 >>>random.randint(1,11) #隨機(jī)生成一個(gè)數(shù)(包含開始和結(jié)束的數(shù)字)
-
range
語法:range([start,]stop[,step=1])
- 這個(gè)BIF有三個(gè)參數(shù)侦镇,其中用中括號(hào)括起來的兩個(gè)表示這兩個(gè)參數(shù)是可選的
- step=1表示第三個(gè)參數(shù)的默認(rèn)值是1
- range這個(gè)BIF的作用是生成一個(gè)從start參數(shù)的值開始到stop參數(shù)的值結(jié)束的數(shù)字序列(包括start參數(shù)哦的值,不包括stop參數(shù)的值)>>> for i in range(4): ... print(i,end=' ') ... 0 1 2 3 >>> for i in range(0,4,2): ... print(i,end=' ') ... 0 2
-
datetime 模塊為日期和時(shí)間處理同時(shí)提供了簡(jiǎn)單和復(fù)雜的方法织阅。支持日期和時(shí)間算法的同時(shí)壳繁,實(shí)現(xiàn)的重點(diǎn)放在更有效的處理和格式化輸出。該模塊還支持時(shí)區(qū)處理荔棉。
>>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368
-
-
Python中有split()和os.path.split()兩個(gè)函數(shù)闹炉,具體作用如下:
- split():拆分字符串。通過指定分隔符對(duì)字符串進(jìn)行切片润樱,并返回分割后的字符串列表(list)
- os.path.split():按照路徑將文件名和路徑分割開
-
1渣触、split()函數(shù)
語法:str.split(str="",num=string.count(str))[n]
-
參數(shù)說明:
- str:表示為分隔符,默認(rèn)為空格壹若,但是不能為空('')嗅钻。若字符串中沒有分隔符,則把整個(gè)字符串作為列表的一個(gè)元素
- num:表示分割次數(shù)店展。如果存在參數(shù)num养篓,則僅分隔成<font color=red>num+1</font> 個(gè)子字符串,并且每一個(gè)子字符串可以賦給新的變量
- n:表示選取第n個(gè)分片
注意:當(dāng)使用空格作為分隔符時(shí)壁查,對(duì)于中間為空的項(xiàng)會(huì)自動(dòng)忽略
-
splitlines() 以換行符分割字符串
>>>fh = open('abc.txt') >>>flines = fh.read().splitlines() >>>lines
-
2、os.path.split()函數(shù)
語法:os.path.split('PATH')
-
參數(shù)說明:
- PATH指一個(gè)文件的全路徑作為參數(shù):
- 如果給出的是一個(gè)目錄和文件名剔应,則輸出路徑和文件名
- 如果給出的是一個(gè)目錄名睡腿,則輸出路徑和為空文件名
-
3、分離字符串
string = "www.gziscas.com.cn"
- 1.以'.'為分隔符
>>>print(string.split('.')) ['www', 'gziscas', 'com', 'cn']
- 2.分割兩次
>>>print(string.split('.'峻贮,2)) ['www', 'gziscas', 'com.cn']
- 3.分割兩次席怪,并取序列為1的項(xiàng)
>>>print(string.split('.',2)[1]) gziscas
- 4.分割兩次,并把分割后的三個(gè)部分保存到三個(gè)文件
>>>u1, u2, u3 =string.split('.',2) >>>print(u1) >>>print(u2) >>>print(u3) www gziscas com.cn
- 1.以'.'為分隔符
-
4纤控、分離文件名和路徑
``` >>>import os >>>print(os.path.split('/dodo/soft/python/')) ('/dodo/soft/python', '') >>>print(os.path.split('/dodo/soft/python')) ('/dodo/soft', 'python') ```
-
-
切片賦值
>>>a = [123,'abc',4.56,['test1','test2']] >>>print(a) >>>a[1:3] =[1,2] >>>print(a) [123, 'abc', 4.56, ['test1', 'test2']] [123, 1, 2, ['test1', 'test2']]
-
字符串對(duì)象的常用方法
- count 計(jì)算字符串中包含的多少個(gè)指定的子字符串
>>> '123 123 789'.count('123') 2
- endswith 檢查字符串是否以指定的字符串結(jié)尾
>>>'139 123 789'.endswith('89') True
- startswith 檢查字符串是否以指定的字符串開頭
>>>'185 123 789'.startswith('123') False
- find 返回指定的子字符串在字符串中出現(xiàn)的位置
>>> '12345678'.find('4566') 3
- 如果有多個(gè)挂捻,返回第一個(gè)的位置
>>>'ok,good,name'.find(',') 2
- 還可以指定從什么位置開始查找
>>>'ok,good,name'.find(',',3) 7
- isalpha 檢查字符串中都是字母
>>>'abc1'.isalpha() False
- isdigit 檢查字符串中是否都是數(shù)字
>>>'abc1'.isdigit() False
- str.join 將sequence類型的參數(shù)的元素字符串合并(連接)到一個(gè)字符串,string作為分隔符
>>>';'.join(['i','love','you']) i;love;you >>>''.join(['i','love','you']) iloveyou >>>b= ',' >>>a=b.join(['i','love','you']) >>>print(a) i,love,you
- split講字符串分割為幾個(gè)子字符串船万,參數(shù)為分隔符,返回結(jié)果存在一個(gè)list里
>>>'i like play football'.split(' ') # 以空格作為分隔符 ['i', 'like', 'play', 'football']
- replace 替換字符串里面指定的子字符串
>>>a = 'Tom is a dog. Snoopy is a dog' >>>b = a.replace('dog','pig') >>>print(a) >>>print(b) Tom is a dog. Snoopy is a dog Tom is a pig. Snoopy is a pig
- 如果有多個(gè)挂捻,返回第一個(gè)的位置
- count 計(jì)算字符串中包含的多少個(gè)指定的子字符串
-
格式化
- % 數(shù)字代表長(zhǎng)度刻撒,正數(shù)是右對(duì)齊,負(fù)數(shù)是左對(duì)齊
>>>vs = [('hasen1',89898),('hasen1112',4444)] >>>fs = ''' >>>%-10s salary: %10d $ >>>%-10s salary: %10d $ >>>''' >>>print(fs % (vs[0][0],vs[0][1],vs[1][0],vs[1][1])) hasen1 salary: 89898 $ hasen1112 salary: 4444 $
-
format
- 基本格式
>>>print('{}'.format(56)) >>>print('{:10}'.format(56)) # 右對(duì)齊 >>>print('{:<10}'.format(56)) # 左對(duì)齊 >>>print('{:010}'.format(56)) #補(bǔ)0 56 56 56 0000000056
- 如果字符串內(nèi)本身含有{}耿导,則需要用兩個(gè)
>>>print('{} 他說{{你好}}'.format(123.222)) 123.222 他說{你好}
- 簡(jiǎn)易格式(python 3.6以后)
>>>name = 'hasen' >>>print(f'he said his name is {name}') he said his name is hasen >>>print(f'{123.444:.2f}') 123.44
- % 數(shù)字代表長(zhǎng)度刻撒,正數(shù)是右對(duì)齊,負(fù)數(shù)是左對(duì)齊
which python(which python3) 查詢python的path
- tell 當(dāng)前指針位置
>>>fh = open('abc.txt') >>>fh.tell() 0
- seek 移動(dòng)指針
>>>fh = open('abc.txt') >>>fh.tell() 0 >>>fh.seek(2) #向后移動(dòng)兩個(gè)位置 >>>fh.tell() 2 >>>fh.seek(2,0) #0-從開始位置向后移動(dòng)兩個(gè)位置 >>>fh.tell() 2 >>>fh.seek(2,1) #1-從當(dāng)前位置向后移動(dòng)兩個(gè)位置 >>>fh.tell() 4 >>>fh.seek(-2,2) #2-從結(jié)束位置向前移動(dòng)兩位 >>>fh.tell()
-
字典(dict)
- get方法:如果查不到則返歸指定的值
>>>dict2 = {'name':'jack','age':40} >>>dict2['age'] 40 >>>dict2.get('age1',10) 10
- 取字典里的值
for name in dict #取出key for name,info in dict.items() #取出key和value for keys in dict.keys() #取出key for values in dict.values()#取出value
- 清空字典
dict.clear()# 清除內(nèi)容 dict = {} # 定義為一個(gè)新的字典声怔,如果是在其他處調(diào)用,則原dict不變
- 增加另一個(gè)dict的內(nèi)容
>>>d = {1:1,2:2,3:3} >>>d {1: 1, 2: 2, 3: 3} >>>d.update({4:4,5:5}) >>>d {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
-
pip使用
- 安裝
pip install xxx
- 卸載
pip uninstall xxx
- 更新
pip install xxx -u
- 安裝
-
函數(shù)注釋
def count(info): ''' :param info: 格式:'姓名1,:age1,姓名2:age2舱呻,...' :type info:str :return: (maxNumAge, maxNum) :rtype:list 計(jì)算字符串內(nèi)哪個(gè)年齡的人數(shù)最多醋火,并返回人數(shù)最多的年齡和該年齡的人數(shù) ''' pass a = 'hasen1 :13,tom mark : 33,hasen3:13,hasen4:13,hasen5:33, hasen5:40' count(a)
- :param a -->指明參數(shù)為a
- :type a:int -->指明參數(shù)a的類型為int
- :return:a*2 -->指明返回的內(nèi)容
- :rtype:int -->指明返回的類型
- 調(diào)用函數(shù)時(shí),按住ctrl,鼠標(biāo)指向調(diào)用參數(shù)的位置可以查看該函數(shù)的參數(shù)個(gè)數(shù)芥驳、類型柿冲,以及返回類型
顯示內(nèi)容如下: ---def count(info) ---inferred type:(info:str) -> list
- 調(diào)試
-
方法一:IDE debug
常用于開發(fā)環(huán)境中:
方便、快捷;
查看變量兆旬、表達(dá)式的值- 設(shè)置斷點(diǎn)
- 執(zhí)行:Debug 'xx'(執(zhí)行到第一個(gè)斷點(diǎn)前面的語句為止(斷點(diǎn)處語句還未執(zhí)行到))
- 繼續(xù)執(zhí)行
- Resume Program(F9)繼續(xù)執(zhí)行(執(zhí)行到下一個(gè)斷點(diǎn)前)
- Step Over(F8)單步執(zhí)行(不進(jìn)入循環(huán)體假抄,每次執(zhí)行完本行)
- Step Into(F7)單步執(zhí)行(進(jìn)入循環(huán)體)
- Step Into My Code(Alt+Shift+F7)單步執(zhí)行(進(jìn)入循環(huán)體,僅進(jìn)入我的代碼)
- Step Over(Shift+F8)單步執(zhí)行(如果已進(jìn)入循環(huán)體內(nèi)爵憎,按此按鈕可提前執(zhí)行完循環(huán)并跳出循環(huán)體)
- Stop 'xxx'(Ctrl+F2)結(jié)束debug
-
-
方法二:打印信息(pprint)(日志信息)
常用在沒有IDE的時(shí)候:臨時(shí)任務(wù)慨亲;生產(chǎn)環(huán)境(bug不方便重現(xiàn);用log方法宝鼓,tail/tailf查看日志文件)
# pprint 支持打印列表和字典 >>>from pprint import pprint >>>a = [1,2,3,4,6] >>>pprint(a)
-
- 判斷數(shù)據(jù)類型
- type 查詢類型
-
isinstance(a,b) 判斷類型(推薦使用)
a是否為b類型,返回bool型(True or False)
>>>type(3) <class 'int'> >>>isintance(3,int) True >>>isintance(3,str) False
- 條件判斷
-
三元操作符
語法:x if 條件 else y -->如果條件為真則結(jié)果為x 否則為y
>>>a,b = 3,4 >>>small = a if a<b else b >>>print(small) 3
-
斷言(assert)
當(dāng)此關(guān)鍵字后面的條件為假時(shí)刑棵,程序自動(dòng)崩潰并拋出AssertionError的異常
一般來說我們可以用Ta在程序中植入檢查點(diǎn),當(dāng)需要確保程序中的某個(gè)條件一定為真才能讓程序正常工作的話愚铡,assert關(guān)鍵字就非常有用了蛉签。
語法格式:assert 表達(dá)式 [, 參數(shù)]
>>>assert 3>4 AssertionError >>>assert 5<4,'XX' Traceback (most recent call last): File "lhytest.py", line 2, in <module> assert 5<4,'XX' AssertionError: XX
-
- 連接mysql數(shù)據(jù)庫(kù)
import pymysql.cursors connect = pymysql.Connect( host='199.09.09.99', port =3306, user='root', password='root', database='healthywalk' ) cursor = connect.cursor() cursor.execute('select answers from questionnaire ') value= cursor.fetchall() print(value)
- 調(diào)用默認(rèn)瀏覽器打開某個(gè)網(wǎng)址
import webbrowser webbrowser.open('http://www.baidu.com')