1. 程式人生 > >二、python沈澱之路~~字符串屬性(str)

二、python沈澱之路~~字符串屬性(str)

格式 否則 pytho 指定 spa nds 輸出 位置 ase

1、capitalize的用法:即將輸出字符串首字母大寫

1 test = "heLLo"
2 v = test.capitalize()
3 print(v)

結果:Hello。

2、casefold和lower的用法以及區別

1 test = "heLLo"
2 v1 = test.casefold()
3 print(v1)
4 v2 = test.lower()
5 print(v2)

結果:hello,hello。結果相同,但是適用範圍不一樣。casefold可以識別世界上大部分國家的 語言轉換,而 lower只適用於英語

3、center的用法

1 test = "heLLo
" 2 v3 = test.center(20) 3 print(v3) 4 v4 = test.center(20,"*") 5 print(v4)

結果:

1        heLLo        
2 *******heLLo********

輸出設置寬度,並且將字符串放置中間,而且兩邊可以設置填充物。

4、count、endswith,startswith三個的用法

1 test = "helloworldhello"
2 v = test.count("l")  #統計 l 出現的次數
3 v1 = test.count("l",3,5)  #在3到5的範圍內統計“l”出現的次數
4 print(v) 5 v3 = test.endswith("o") #判斷字符串是否已"l"結尾的,是則返回True,否則返回False 6 v4 = test.endswith("w",2,7)#在2到7的範圍內判斷是否以"w"結尾 7 print(v3) 8 print(v4)
1 5
2 True
3 False

startswith 的用法與endswith一樣

5、find 和index的用法以及區別

1 test = "helloworldhello"
2 v = test.find("w")
3 v1 = test.find("l")
4 print(v,v1)
5 v2 = test.find("l",6,10) 6 print(v2) 7 #v3 = test.index("l")
1 5 2
2 8

find和index都是找某個子字符串的位置,而且可以指定範圍的尋找。區別在於find找不到時返回-1,index找不到時會報錯

6、format和format_map格式化字符串的用法

1 test = i an {name},age {a}
2 test1 = i am {0},age{1}
3 v = test.format(name="zhongguo",a=18)  #修改內容
4 v1 = test1.format("xiaoming",18)  #自動匹配位置
5 print(v)
6 print(v1)
7 v2 = test.format_map({"name":zhong,a:18})#format_map的用法就是{}裏面加字典形式的內容
8 print(v2)
1 i an zhongguo,age 18
2 i am xiaoming,age18
3 i an zhong,age 18

二、python沈澱之路~~字符串屬性(str)