Python中字元串常見操作總結:
Num01–>find
檢測 str 是否包含在 mystr中,如果是,傳回開始的索引值;否則傳回-。也可以指定在一定的範圍内。
mystr.find(str, start=, end=len(mystr))
Num02–>index
跟find()方法一樣,隻不過如果str不在 mystr中會報一個異常.
mystr.index(str, start=, end=len(mystr))
Num03–>count
傳回 str在start和end之間 在 mystr裡面出現的次數
mystr.count(str, start=, end=len(mystr))
Num04–>replace
把 mystr 中的 str1 替換成 str2,如果 count 指定,則替換不超過 count 次.
mystr.replace(str1, str2, mystr.count(str1))
Num05–>splite
以 str 為分隔符切片 mystr,如果 maxsplit有指定值,則僅分隔 maxsplit 個子字元串
mystr.split(str=" ", )
Num06–>capitalize
把字元串的第一個字元大寫
mystr.capitalize()
Num07–>title
把字元串的每個單詞首字母大寫
a = "hello xiaoke"
a.title()
'Hello Xiaoke'
Num08–>startswith
檢查字元串是否是以 obj 開頭, 是則傳回 True,否則傳回 False
mystr.startswith(obj)
Num09–>endswith
檢查字元串是否以obj結束,如果是傳回True,否則傳回 False.
mystr.endswith(obj)
Num10–>lower
轉換 mystr 中所有大寫字元為小寫
mystr.lower()
Num11–>upper
轉換 mystr 中的小寫字母為大寫
mystr.upper()
Num12–>ljust
傳回一個原字元串左對齊,并使用空格填充至長度 width 的新字元串
mystr.ljust(width)
Num13–>rjust
傳回一個原字元串右對齊,并使用空格填充至長度 width 的新字元串
mystr.rjust(width)
Num14–>center
傳回一個原字元串居中,并使用空格填充至長度 width 的新字元串
mystr.center(width)
Num15–>lstrip
删除 mystr 左邊的空白字元
mystr.lstrip()
Num16–>rstrip
删除 mystr 字元串末尾的空白字元
mystr.rstrip()
Num17–>strip
删除mystr字元串兩端的空白字元
>>> a = "\n\t xiaoke \t\n"
>>> a.strip()
'xiaoke'
Num18–>rfind
類似于 find()函數,不過是從右邊開始查找.
mystr.rfind(str, start=,end=len(mystr) )
Num19–>rindex
類似于 index(),不過是從右邊開始.
mystr.rindex( str, start=,end=len(mystr))
Num20–>partition
把mystr以str分割成三部分,str前,str和str後
mystr.partition(str)
Num21–>rpartition
類似于 partition()函數,不過是從右邊開始.
mystr.rpartition(str)
Num22–>splitlines
按照行分隔,傳回一個包含各行作為元素的清單
mystr.splitlines()
Num23–>isalpha
如果 mystr 所有字元都是字母 則傳回 True,否則傳回 False
mystr.isalpha()
Num24–>isdigit
如果 mystr 隻包含數字則傳回 True 否則傳回 False.
mystr.isdigit()
Num25–>isalnum
如果 mystr 所有字元都是字母或數字則傳回 True,否則傳回 False
mystr.isalnum()
Num26–>isspace
如果 mystr 中隻包含空格,則傳回 True,否則傳回 False.
mystr.isspace()
Num27–>join
mystr 中每個字元後面插入str,構造出一個新的字元串
mystr.join(str)
### 面試題:如下字元串,含有空格和換行符,傳回使用空格或者'\t'分割後的倒數第二個子串
test="hello world \t ha he \nhei \nher"
# 以\t分割
newTest=test.split("\t")
print(newTest)
print("以\\t\t分割後的倒數第二個子串:%s"%newTest[len(newTest)-])
# 以空格分割
newTest=test.split()
print(newTest)
print("以空格分割後的倒數第二個子串:%s"%newTest[len(newTest)-])
結果如下:
['hello world ', ' ha he \nhei \nher']
以\t 分割後的倒數第二個子串:hello world
['hello', 'world', 'ha', 'he', 'hei', 'her']
以空格分割後的倒數第二個子串:hei