Python基礎總結(字符串常用,數字類型轉換,基本運算符與流程控制)
一.字符串常用操作
#Python strip() 方法用於移除字符串頭尾指定的字符(默認為空格) name=‘*egon**‘ print(name.strip(‘*‘))#移除 name 變量對應的值兩邊的*,並輸出處理結果 print(name.lstrip(‘*‘))#移除 name 變量左邊的*,並輸出處理結果 print(name.rstrip(‘*‘))#移除 name 變量右邊的*,並輸出處理結果 #startswith,endswith name=‘alex_SB‘ print(name.endswith(‘SB‘))#判斷 name 變量對應的值是否以 "SB" 結尾,並輸出結果字符串常用操作print(name.startswith(‘alex‘))#判斷 name 變量對應的值是否以 "alex" 開頭,並輸出結果 #replace name=‘alex say :i have one tesla,my name is alex‘#將 name 變量對應的值中的第一個“alex” 替換為 “SB”,並輸出結果 print(name.replace(‘alex‘,‘SB‘,1))#若數字1變為2,則兩個alex都為SB #format的三種玩法,定義打印順序 res=‘{} {} {}‘.format(‘egon‘,18,‘male‘) res=‘{1} {0} {1}‘.format(‘egon‘,18,‘male‘) res=‘{name} {age} {sex}‘.format(sex=‘male‘,name=‘egon‘,age=18) res=‘{name} {sex} {age}‘.format(sex=‘male‘,name=‘egon‘,age=18) print(res) #find,rfind,index,rindex,count name=‘egon say hello‘ print(name.find(‘o‘,1,3)) #顧頭不顧尾,找不到則返回-1不會報錯,找到了則顯示索引, # 即在第一至第4個字符中查找字符“O” # print(name.index(‘e‘,2,4)) #同上,但是找不到會報錯print(name.count(‘e‘,1,3)) #顧頭不顧尾,如果不指定範圍則查找所有 # 用於統計字符串裏某個字符出現的次數。可選參數為在字符串搜索的開始與結束位置 #split name=‘root:x:0:0::/root:/bin/bash‘ print(name.split(‘:‘)) #默認分隔符為空格 name=‘C:/a/b/c/d.txt‘ #只想拿到頂級目錄 print(name.split(‘/‘,1)) name=‘a|b|c‘ print(name.rsplit(‘|‘,1)) #從右開始切分,移除| #join:Python join() 方法用於將序列中的元素以指定的字符連接生成一個新的字符串 tag=‘ ‘ print(tag.join([‘egon‘,‘say‘,‘hello‘,‘world‘])) #可叠代對象必須都是字符串 #center,ljust,rjust,zfill name=‘egon‘ print(name.center(30,‘-‘))#用-填充在兩邊位置 print(name.ljust(30,‘*‘))#用*填充在右邊位置 print(name.rjust(30,‘*‘))#用*填充在左邊位置 print(name.zfill(50)) #用0填充在左邊 #expandtabs:把字符串中的 tab 符號(‘\t‘)轉為空格,tab 符號(‘\t‘)默認的空格數是 8 name=‘egon\thello‘ print(name) print(name.expandtabs(1))#使用1個空格替換 ‘\t‘ #lower,upper name=‘egon‘ print(name.lower())# 方法轉換字符串中所有大寫字符為小寫 print(name.upper())# 方法轉換字符串中所有小寫字符為大寫 #captalize,swapcase,title print(name.capitalize()) #首字母大寫 print(name.swapcase()) #大小寫翻轉 msg=‘egon say hi‘ print(msg.title()) #每個單詞的首字母大寫 #is數字系列 #在python3中 num1=b‘4‘ #bytes num2=u‘4‘ #unicode,python3中無需加u就是unicode num3=‘四‘ #中文數字 num4=‘Ⅳ‘ #羅馬數字 #isdigt:bytes,unicode print(num1.isdigit()) #True print(num2.isdigit()) #True print(num3.isdigit()) #False print(num4.isdigit()) #False #isdecimal:uncicode #bytes類型無isdecimal方法 print(num2.isdecimal()) #True print(num3.isdecimal()) #False print(num4.isdecimal()) #False #isnumberic:unicode,中文數字,羅馬數字 #bytes類型無isnumberic方法 print(num2.isnumeric()) #True print(num3.isnumeric()) #True print(num4.isnumeric()) #True #三者不能判斷浮點數 num5=‘4.3‘ print(num5.isdigit()) print(num5.isdecimal()) print(num5.isnumeric()) ‘‘‘ 總結: 最常用的是isdigit,可以判斷bytes和unicode類型,這也是最常見的數字應用場景 如果要判斷中文數字或羅馬數字,則需要用到isnumeric ‘‘‘ #is其他 print(‘===>‘) name=‘egon123‘ print(name.isalnum()) #判斷字符串由字母和數字組成 print(name.isalpha()) #判斷字符串只由字母組成 print(name.isidentifier()) print(name.islower())#lower() 方法檢測字符串是否由小寫字母組成。 print(name.isupper())#isupper() 方法檢測字符串中所有的字母是否都為大寫。 print(name.isspace())#描述 Python isspace() 方法檢測字符串是否只由空格組成。 print(name.istitle())#描述 istitle() 方法檢測字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫 字符串常用
二.數據類型內置轉換函數
註:針對acsii表unichr在python2.7中比chr的範圍更大。在python3中chr內置了unchir
三.運算符
1.算數運算
2.比較運算
3.賦值運算
4.位運算
註: ~ 舉例: ~5 = -6 解釋: 將二進制數+1之後乘以-1,即~x = -(x+1),-(101 + 1) = -110
按位反轉僅能用在數字前面。所以寫成 3+~5 可以得到結果-3,寫成3~5就出錯了
5.邏輯運算
and註解:
- 在Python 中,and 和 or 執行布爾邏輯演算,如你所期待的一樣,但是它們並不返回布爾值;而是,返回它們實際進行比較的值之一。
- 在布爾上下文中從左到右演算表達式的值,如果布爾上下文中的所有值都為真,那麽 and 返回最後一個值。
- 如果布爾上下文中的某個值為假,則 and 返回第一個假值
or註解:
- 使用 or 時,在布爾上下文中從左到右演算值,就像 and 一樣。如果有一個值為真,or 立刻返回該值
- 如果所有的值都為假,or 返回最後一個假值
- 註意 or 在布爾上下文中會一直進行表達式演算直到找到第一個真值,然後就會忽略剩余的比較值
and-or結合使用:
- 結合了前面的兩種語法,推理即可。
- 為加強程序可讀性,最好與括號連用,例如:
(1 and ‘x‘) or ‘y‘
6.成員運算
7.身份運算
8.運算符的優先級:自上而下,優先級從高到低
四.流程控制
1、if語法:
if 條件:
子代碼
elif 條件:
子代碼
else:
子代碼
例如:
age=63 age = int(input("老男孩的age是:") ) if age > 63 : print("too big") elif age < 63 : print("too small") else: print("you get it") 猜年齡猜年齡
總結:
- if 後表達式返回值為True則執行其子代碼塊,然後此if語句到此終結,否則進入下一分支判斷,直到滿足其中一個分支,執行後終結if
- expression可以引入運算符:not,and,or,is,is not
- 多重expression為加強可讀性最好用括號包含
- if與else縮進級別一致表示是一對
- elif與else都是可選的
- 一個if判斷最多只有一個else但是可以有多個elif
- else代表if判斷的終結
- expession可以是返回值為布爾值的表達式(例x>1,x is not None)的形式,也可是單個標準對象(例 x=1;if x:print(‘ok‘))
- 所有標準對象均可用於布爾測試,同類型的對象之間可以比較大小。每個對象天生具有布 爾 True 或 False 值。空對象、值為零的任何數字或者 Null 對象 None 的布爾值都是 False。
下列對象的布爾值是 False
2、while循環
作用:
while循環的本質就是讓計算機在滿足某一條件的前提下去重復做同一件事情(即while循環為條件循環,包含:1.條件計數循環,2條件無限循環)
這一條件指:條件表達式
同一件事指:while循環體包含的代碼塊
重復的事情例如:從1加到10000,求1-10000內所有奇數,服務等待連接
語法:
while 條件
執行子代碼
滿足條件循環執行直到條件不滿足。
死循環
while true:
print(ok)
循環終止語句:
- break用於完全結束一個循環,跳出循環體執行循環後面的語句
- continue和break有點類似,區別在於continue只是終止本次循環,接著還執行後面的循環,break則完全終止循環
count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本層循環,即徹底終結這一個/層while循環‘) break print(‘the loop is %s‘ %count) break跳出本層循環break跳出本層循環
count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本次循環,即這一次循環continue之後的代碼不再執行,進入下一次循環‘) continue print(‘the loop is %s‘ %count) continue跳出本次循環continue跳出本次循環
count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本次循環,即這一次循環continue之後的代碼不再執行,進入下一次循環‘) continue print(‘the loop is %s‘ %count) else: print(‘循環不被break打斷,即正常結束,就會執行else後代碼塊‘) count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本次循環,即這一次循環continue之後的代碼不再執行,進入下一次循環‘) break print(‘the loop is %s‘ %count) else: print(‘循環被break打斷,即非正常結束,就不會執行else後代碼塊‘) else在循環完成後執行,break會跳過elseelse在循環完成後執行,break會跳過else
name= "user" passwd="password" n=1 while n<=3: x = 3 - n name = input("請輸入用戶名:") if name=="user": passwd = input("請輸入密碼:") if passwd == "password": print("登陸成功") break else: print("密碼錯誤,請重新輸入,您還有",x,"次機會") while n<=2: y = 2 - n passwd = input("請輸入密碼:") if name == "user" and passwd == "password": print("登陸成功") break else: print("密碼錯誤,請重新輸入,您還有",y,"次機會") n+=1 else : print("用戶名有誤,請重新登陸,您還有",x,"次機會") n+=1 用戶登錄三次用戶三次登錄
i=1 n=0 while i<=99: if i % 2 == 1: n=n+i else: n=n-i i+=1 print(n) 1-2+3-4+5 ... 99的所有數的和1-2+3-4+5.......99的所有數的和
Cyle = 0 while Cyle <= 9: Cyle += 1 if Cyle == 7: print(" ") else: print(Cyle) 使用while循環輸出1 2 3 4 5 6 8 9 10使用while循環輸出1 2 3 4 5 6 8 9 10
i=1 n=0 while i<=100: n =n +i i+=1 print(n)求1-100所有數的和
#奇數 i=0 while i<100: i+=1 if i % 2 == 1: print(i) #偶數 i=0 while i<100: i+=1 if i % 2 == 0: print(i) 輸出 1-100 內的所有奇數、偶數輸出1-100內所有的奇數,偶數
Python的字符串內建函數
python的常用內建函數如下:
序號 | 方法及描述 |
---|---|
1 |
capitalize() |
2 |
center(width, fillchar) 返回一個指定的寬度 width 居中的字符串,fillchar 為填充的字符,默認為空格。 |
3 |
count(str, beg= 0,end=len(string)) 返回 str 在 string 裏面出現的次數,如果 beg 或者 end 指定則返回指定範圍內 str 出現的次數 |
4 |
bytes.decode(encoding="utf-8", errors="strict") Python3 中沒有 decode 方法,但我們可以使用 bytes 對象的 decode() 方法來解碼給定的 bytes 對象,這個 bytes 對象可以由 str.encode() 來編碼返回。 |
5 |
encode(encoding=‘UTF-8‘,errors=‘strict‘) 以 encoding 指定的編碼格式編碼字符串,如果出錯默認報一個ValueError 的異常,除非 errors 指定的是‘ignore‘或者‘replace‘ |
6 |
endswith(suffix, beg=0, end=len(string)) |
7 |
expandtabs(tabsize=8) 把字符串 string 中的 tab 符號轉為空格,tab 符號默認的空格數是 8 。 |
8 |
find(str, beg=0 end=len(string)) 檢測 str 是否包含在字符串中 中,如果 beg 和 end 指定範圍,則檢查是否包含在指定範圍內,如果是返回開始的索引值,否則返回-1 |
9 |
index(str, beg=0, end=len(string)) 跟find()方法一樣,只不過如果str不在字符串中會報一個異常. |
10 |
isalnum() 如果字符串至少有一個字符並且所有字符都是字母或數字則返 回 True,否則返回 False |
11 |
isalpha() 如果字符串至少有一個字符並且所有字符都是字母則返回 True, 否則返回 False |
12 |
isdigit() 如果字符串只包含數字則返回 True 否則返回 False.. |
13 |
islower() 如果字符串中包含至少一個區分大小寫的字符,並且所有這些(區分大小寫的)字符都是小寫,則返回 True,否則返回 False |
14 |
isnumeric() 如果字符串中只包含數字字符,則返回 True,否則返回 False |
15 |
isspace() 如果字符串中只包含空格,則返回 True,否則返回 False. |
16 |
istitle() 如果字符串是標題化的(見 title())則返回 True,否則返回 False |
17 |
isupper() 如果字符串中包含至少一個區分大小寫的字符,並且所有這些(區分大小寫的)字符都是大寫,則返回 True,否則返回 False |
18 |
join(seq) 以指定字符串作為分隔符,將 seq 中所有的元素(的字符串表示)合並為一個新的字符串 |
19 |
len(string) 返回字符串長度 |
20 |
ljust(width[, fillchar]) 返回一個原字符串左對齊,並使用 fillchar 填充至長度 width 的新字符串,fillchar 默認為空格。 |
21 |
lower() 轉換字符串中所有大寫字符為小寫. |
22 |
lstrip() 截掉字符串左邊的空格或指定字符。 |
23 |
maketrans() 創建字符映射的轉換表,對於接受兩個參數的最簡單的調用方式,第一個參數是字符串,表示需要轉換的字符,第二個參數也是字符串表示轉換的目標。 |
24 |
max(str) 返回字符串 str 中最大的字母。 |
25 |
min(str) 返回字符串 str 中最小的字母。 |
26 |
replace(old, new [, max]) 把 將字符串中的 str1 替換成 str2,如果 max 指定,則替換不超過 max 次。 |
27 |
rfind(str, beg=0,end=len(string)) 類似於 find()函數,不過是從右邊開始查找. |
28 |
rindex( str, beg=0, end=len(string)) 類似於 index(),不過是從右邊開始. |
29 |
rjust(width,[, fillchar]) 返回一個原字符串右對齊,並使用fillchar(默認空格)填充至長度 width 的新字符串 |
30 |
rstrip() 刪除字符串字符串末尾的空格. |
31 |
split(str="", num=string.count(str)) num=string.count(str)) 以 str 為分隔符截取字符串,如果 num 有指定值,則僅截取 num 個子字符串 |
32 |
splitlines([keepends]) 按照行(‘\r‘, ‘\r\n‘, \n‘)分隔,返回一個包含各行作為元素的列表,如果參數 keepends 為 False,不包含換行符,如果為 True,則保留換行符。 |
33 |
startswith(str, beg=0,end=len(string)) 檢查字符串是否是以 obj 開頭,是則返回 True,否則返回 False。如果beg 和 end 指定值,則在指定範圍內檢查。 |
34 |
strip([chars]) 在字符串上執行 lstrip()和 rstrip() |
35 |
swapcase() 將字符串中大寫轉換為小寫,小寫轉換為大寫 |
36 |
title() 返回"標題化"的字符串,就是說所有單詞都是以大寫開始,其余字母均為小寫(見 istitle()) |
37 |
translate(table, deletechars="") 根據 str 給出的表(包含 256 個字符)轉換 string 的字符, 要過濾掉的字符放到 deletechars 參數中 |
38 |
upper() 轉換字符串中的小寫字母為大寫 |
39 |
zfill (width) 返回長度為 width 的字符串,原字符串右對齊,前面填充0 |
40 |
isdecimal() 檢查字符串是否只包含十進制字符,如果是返回 true,否則返回 false。 |
Python基礎總結(字符串常用,數字類型轉換,基本運算符與流程控制)