1. 程式人生 > >python 基礎資料結構之字串操作

python 基礎資料結構之字串操作

#切割部分
s = 'I love you more than i can say' # 切割字串 # sep:指定按照什麼進行切割,預設按照空格切割 # maxsplit:指定最大切割次數,預設不限制次數 # ret = s.split(sep='abc', maxsplit=1) # 從右邊進行切割 ret = s.rsplit(' ', maxsplit=7)#以空格切割 print(ret) #等價於下面操作 s = 'I love you more than i can say' ret = s.split() print(ret)
s = 'Hello\nworld'
# 按照換行進行切割

print(s.splitlines())
s = 'I love you more than i can say'
ret = s.split()
print(ret)
#字串拼接
s2 = '*'.join(ret)
print(s2)#I*love*you*more*than*i*can*say
#查詢操作
s = 'Hi buddy, if you have something to say, than say; if you have nothing to say, than go.' # 子串查詢:找到首次出現的位置,返回下標,找不到返回-1 ret = s.find('hello') print(ret)#
-1 # 從後面查詢 ret = s.rfind('to')#70 print(ret) print(s[70],s[71])#t o # 統計子串出現的次數 ret = s.count('if') print(ret)#2
#判斷部分
# 判斷是否已指定內容開頭
s = 'Hi buddy, if you have something to say, than say; if you have nothing to say, than go.'
ret = s.startswith('Hi')
print(ret)#True
# 判斷是否已指定內容結尾
ret 
= s.endswith('go.') print(ret)#True s = 'hellO worlD!' # 轉換為全大寫 print(s.upper())#HELLO WORLD! # 轉換為全小寫 print(s.lower())#hello world! # 大小寫轉換 print(s.swapcase())#HELLo WORLd! # 首字母大寫 print(s.capitalize())#Hello world! # 每個單詞首字母大寫 print(s.title())#Hello World! # 用指定的內容替換指定內容,還可以值替換次數 print(s.replace('l', 'L', 2))#heLLO worlD! s = 'abcABC2' # 是否是全大寫 print(s.isupper())#False # 是否是全小寫 print(s.islower())#False # 是否每個單詞首字母都大寫 print(s.istitle())#False # 是否是全數字字元 print(s.isdecimal())#False # 是否是全字母 print(s.isalpha())#False # 是否全是字母或數字 print(s.isalnum())#False