python基礎-字串常用方法
注:記憶體決定了 各種方法都是重新生產新的字元,而不是在原字元上編輯
1.casefold,lower-所有大寫字母轉換為小寫字母.islower-是否全是小寫。upper-所有字母轉換為大寫,isupper-是否全是大寫
casefold能識別其它國家的各種小寫,lower只能識別英文字母的小寫。
1 test="Alex" 2 v=test.lower() 3 print(v)
2.center-將字串內容居中,可設定兩側填充的內容
ljust-左對齊,rjust-右對齊
test="abc" v=test.center(10,"*") print(v)
3.count-統計字元有多少個,區間左開右閉
test="AlAx" v=test.count("A",0,2) print(v)
4.startswith,endswith-以xx字串開始,結束,返回bool值,true/false
test="Alex" v1=test.endswith("x") v2=test.startswith("b") print(v1,v2)
5.find,index-返回查詢字元的第一個索引號,字元不存在時,find返回-1,index會報錯
test="Alexl" v1=test.find("l") v2=test.index("l") print(v1,v2)
6.format-格式化。將字串中的佔位符替換為指定的值
test="i am {name},age {age}" v=test.format(name="張三",age=18) print(v)
test="i am %s,age %d"%("張三",18) print(test)
7.isidentifier,isalnum,isalpha,isdecimal,isdigit,isnumeric-是否是標準字元,字母或數字,字母,數字,返回bool
isdecimal只支援阿拉伯數字,isdigit支援特殊的數字,如Ⅱ①,idnumeric 支援漢字數字,如:二
8.expandtabs-將轉義字元(\t,\n)按所填的int引數生成新的字串
test="name\tage\tmail\n張三\t18\t610000\n李四\t20\t000000" v=test.expandtabs(10) print(v)
效果如下
9.isprintable-是否可列印,是否存在不可顯示的字元,如\t,\n
test="ab\tab" v=test.isprintable() print(v)
10.isspace-是否全為空字元,返回bool
test=" 1" v=test.isspace() print(v)
11.title,istitle-將字串轉化為標題格式(即首字母大寫),是否為標題格式
12.join-將字串按指定分隔符分割(非常重要,記住)
test="你好帥" v="_".join(test) print(v)
13.strip,lstrip,rstrip-移除,去除(左移除,右移除),預設移除空白(space),可指定移除字元
test=" Alex" v=test.rstrip("x") print(v)
14.maketrans,translate-先建立字元對映的轉換表,字元對映(轉換表)
intab="aeiou" outab="12345" trantab=str.maketrans(intab,outab) v="hello world" print(v.translate(trantab))
15.partition/rpartition,split- partition按左/右 第一個指定字元分:前,指定字元,後。
split按每個指定字元分:前,後。指定的字元被刪除了
splitlines按照換行('\r', '\r\n', \n')分隔
test="abcdefgchios" v1=test.partition("c") v2=test.split("c") print(v1) print(v2)
16.swapcase-英語中swap是轉換的意思,swapcase方法是把大寫變小寫,小寫變大寫
test="Alex" v=test.swapcase() print(v)
17.字串索引 str[索引號],索引號超出str長度len會報錯,索引號0為第一位字元,-1為倒數第一位字元。也可以為區間如[1:2]
test="aeiou" v1=test[0] v2=test[1:2] print(v1) print(v2)
18.len字元長度
test="a bc" v= len(test) print(v)
19.replace-代替,可指定取代幾個
test="aeiouxabbcc" v=test.replace("a","*",1) print(v)
20.range-範圍,可指定步長
test=range(1,10,2) for x in test: if x==3: continue print(x)
注意:幾個重點方法:
1.join-str1.join(str2)
2.split-切片後切分的字元不保留
3.find-返回索引,不存在則返回-1
4.strip/rstrip-去除
5.upper/lower-全部大寫/小寫
6.replace-代替
7.for迴圈
test=input(">>>") for x in test: print(x)
test=input(">>>") len1=len(test) for x in range(0,len1): print(x,test[x])