python基礎(2)字符串常用方法

python字符串常用方法

 

find(sub[, start[, end]])

在索引start和end之間查找字符串sub
​找到,則返回最左端的索引值,未找到,則返回-1
​start和end都可省略,省略start說明從字符串開頭找
省略end說明查找到字符串結尾,全部省略則查找全部字符串

source_str = "There is a string accessing example"
print(source_str.find('r'))
>>> 3

 

count(sub, start, end)

返回字符串sub在start和end之間出現的次數

source_str = "There is a string accessing example"
print(source_str.count('e'))
>>> 5

 

replace(old, new, count)

old代表需要替換的字符,new代表將要替代的字符,count代表替換的次數(省略則表示全部替換)

source_str = "There is a string accessing example"
print(source_str.replace('i', 'I', 1))
>>> There Is a string accessing example # 把小寫的i替換成了大寫的I

 

split(sep, maxsplit)

以sep為分隔符切片,如果maxsplit有指定值,則僅分割maxsplit個字符串
分割後原來的str類型將轉換成list類型

source_str = "There is a string accessing example"
print(source_str.split(' ', 3))
>>> ['There', 'is', 'a', 'string accessing example'] # 這裡指定maxsplit=3,代表只分割前3個

 

startswith(prefix, start, end)

判斷字符串是否是以prefix開頭,start和end代表從按個下標開始,哪個下標結束

source_str = "There is a string accessing example"
print(source_str.startswith('There', 0, 9))
>>> True

 

endswith(suffix, start, end)

判斷字符串是否以suffix結束,如果是返回True,否則返回False

source_str = "There is a string accessing example"
print(source_str.endswith('example'))
>>> True

 

lower

將所有大寫字符轉換成小寫
 

upper

將所有小寫字符轉換成大寫
 

join

將列表拼接成字符串

list1 = ['ab', 'cd', 'ef']
print(" ".join(list1))
>>> ab cd ef

 

切片反轉

list2 = "hello"
print(list2[::-1])
>>> olleh