天天看點

8種字元串常見操作| 手把手教你入門Python之二十七

上一篇: 詳解字元串| 手把手教你入門Python之二十六 下一篇: 詳解字元集和編碼規則| 手把手教你入門Python之二十八 本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程 《Python入門2020最新大課》 ,主講人姜偉。

字元串常見操作

字元串的常見操作包括:

擷取⻓度:len

查找内容:find,index,rfind,rindex

判斷:startswith,endswith,isalpha,isdigit,isalnum,isspace

計算出現次數:count

替換内容:replace

切割字元串:split,rsplit,splitlines,partition,rpartition

修改⼤⼩寫:capitalize,title,upper,lower

空格處理:ljust,rjust,center,lstrip,rstrip,strip

字元串拼接:join

注意:在Python中,字元串是不可變的!所有的字元串相關⽅法,都不會改變原有的字元串,都是傳回⼀個結果,在這個新的傳回值⾥,保留了執⾏後的結果!

⼀、 len

len函數可以擷取字元串的⻓度。

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(len(mystr)) # 17 擷取字元串的⻓度           

⼆、 查找

查找相關的⽅法,使⽤⽅式⼤緻相同,但是略有差別。

1. find

查找指定内容在字元串中是否存在,如果存在就傳回該内容在字元串中第⼀次出現的開始位置索引值,如果

不存在,則傳回-1.

文法格式:

S.find(sub[, start[, end]]) -> int           

示例:

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.find('好⻛光')) # 10 '好⻛光'第⼀次出現時,'好'所在的位置
print(mystr.find('你好')) # -1 '你好'不存在,傳回 -1
print(mystr.find('⻛', 12)) # 15 從下标12開始查找'⻛',找到⻛所在的位置試15
print(mystr.find('⻛光',1,10)) # -1 從下标1開始到12查找"⻛光",未找到,傳回 -1
           

2. rfind

類似于 find()函數,不過是從右邊開始查找。

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.rfind('好')) # 14           
8種字元串常見操作| 手把手教你入門Python之二十七

3.index

跟find()⽅法⼀樣,隻不過,find⽅法未找到時,傳回-1,⽽str未找到時,會報⼀個異常。

S.index(sub[, start[, end]]) -> int           

4.rindex

類似于 index(),不過是從右邊開始。

8種字元串常見操作| 手把手教你入門Python之二十七
8種字元串常見操作| 手把手教你入門Python之二十七
8種字元串常見操作| 手把手教你入門Python之二十七

三、判斷

python提供了⾮常豐富的⽅法,可以⽤來對⼀個字元串進⾏判斷。

1. startswith

判斷字元串是否以指定内容開始。 文法格式:

S.startswith(prefix[, start[, end]]) -> bool           
mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.startswith('今')) # True
print(mystr.startswith('今⽇')) # False
           

2. endswith

判斷字元串是否以指定内容結束。

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.endswith('好⻛光')) #True
print(mystr.endswith('好⽇⼦')) #False           

3. isalpha

判斷字元串是否是純字⺟。

mystr = 'hello'
print(mystr.isalpha()) # True
mystr = 'hello world'
print(mystr.isalpha()) # False 因為中間有空格           

4. isdigit

判斷⼀個字元串是否是純數字,隻要出現⾮0~9的數字,結果就是False.

mystr = '1234'
print(mystr.isdigit()) # True
mystr = '123.4'
print(mystr.isdigit()) # False
mystr = '-1234'
print(mystr.isdigit()) # False           

5. isalnum

判斷是否由數字和字⺟組成。隻要出現了⾮數字和字⺟,就傳回False.

mystr = 'abcd'
print(mystr.isalnum()) # True
mystr = '1234'
print(mystr.isalnum()) # True
mystr = 'abcd1234'
print(mystr.isalnum()) # True
mystr = 'abcd1234_'
print(mystr.isalnum()) # False           

6. isspace

如果 mystr 中隻包含空格,則傳回 True,否則傳回 False.

mystr = ''
print(mystr.isspace()) # False mystr是⼀個空字元串
mystr = ' '
print(mystr.isspace()) # True 隻有空格
mystr = ' d'
print(mystr.isspace()) # False 除了空格外還有其他内容
           

四、count

傳回 str在start和end之間 在 mystr⾥⾯出現的次數。

文法格式:

S.count(sub[, start[, end]]) -> int
           
mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.count('好')) # 3. '好'字出現三次           

五、替換

替換字元串中指定的内容,如果指定次數count,則替換不會超過count次。

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
newstr = mystr.replace('好', '壞')
print(mystr) # 今天天⽓好晴朗,處處好⻛光呀好⻛光 原字元串未改變!
print(newstr) # 今天天⽓壞晴朗,處處壞⻛光呀壞⻛光 得到的新字元串⾥,'好'被修改成了'壞'
newstr = mystr.replace('好','壞',2) # 指定了替換的次數
print(newstr) # 今天天⽓壞晴朗,處處壞⻛光呀好⻛光 隻有兩處的'好'被替換成了'壞'           

六、内容分隔

内容分隔主要涉及到split,splitlines,partition和rpartition四個⽅法。

split

以指定字元串為分隔符切⽚,如果 maxsplit有指定值,則僅分隔 maxsplit+1 個⼦字元串。傳回的結果是⼀個清單。

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
result = mystr.split() # 沒有指定分隔符,預設使⽤空格,換⾏等空⽩字元進⾏分隔
print(result) #['今天天⽓好晴朗,處處好⻛光呀好⻛光'] 沒有空⽩字元,是以,字元串未被分隔
result = mystr.split('好') # 以 '好' 為分隔符
print(result) # ['今天天⽓', '晴朗,處處','⻛光呀,'⻛光']
result = mystr.split("好",2) # 以 '好' 為分隔符,最多切割成3份
print(result) # ['今天天⽓', '晴朗,處處', '⻛光呀好⻛光']           

rsplit

⽤法和split基本⼀緻,隻不過是從右往左分隔。

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.rsplit('好',1)) #['今天天⽓好晴朗,處處好⻛光呀', '⻛光']           

splitlines

按照⾏分隔,傳回⼀個包含各⾏作為元素的清單。

mystr = 'hello \nworld'
print(mystr.splitlines())           

partition

把mystr以str分割成三部分,str前,str和str後,三部分組成⼀個元組

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.partition('好')) # ('今天天⽓', '好', '晴朗,處處好⻛光呀好⻛光')           

rpartition

類似于 partition()函數,不過是從右邊開始.

mystr = '今天天⽓好晴朗,處處好⻛光呀好⻛光'
print(mystr.rpartition('好')) # ('今天天⽓好晴朗,處處好⻛光呀', '好', '⻛光')           

七、修改⼤⼩寫

修改⼤⼩寫的功能隻對英⽂有效,主要包括,⾸字⺟⼤寫capitalize,每個單詞的⾸字⺟⼤寫title,全⼩寫lower,

全⼤寫upper.

capitalize

第⼀個單詞的⾸字⺟⼤寫。

mystr = 'hello world'
print(mystr.capitalize()) # Hello world           

title

每個單詞的⾸字⺟⼤寫。

mystr = 'hello world'
print(mystr.title()) # Hello World           

lower

所有都變成⼩寫。

mystr = 'hElLo WorLD'
print(mystr.lower()) # hello world           

upper

所有都變成⼤寫。

mystr = 'hello world'
print(mystr.upper()) #HELLO WORLD           
8種字元串常見操作| 手把手教你入門Python之二十七
8種字元串常見操作| 手把手教你入門Python之二十七

⼋、空格處理

Python為我們提供了各種操作字元串⾥表格的⽅法。

1. ljust

傳回指定⻓度的字元串,并在右側使⽤空⽩字元補全(左對⻬)。

str = 'hello'
print(str.ljust(10)) # hello 在右邊補了五個空格           

2. rjust

傳回指定⻓度的字元串,并在左側使⽤空⽩字元補全(右對⻬)。

str = 'hello'
print(str.rjust(10)) # hello在左邊補了五個空格           

3. center

傳回指定⻓度的字元串,并在兩端使⽤空⽩字元補全(居中對⻬)

str = 'hello'
print(str.center(10)) # hello 兩端加空格,讓内容居中           

4. lstrip

删除 mystr 左邊的空⽩字元。

mystr = ' he llo '
print(str.lstrip()) #he llo 隻去掉了左邊的空格,中間和右邊的空格被保留           

5. rstrip

删除 mystr 右邊的空⽩字元。

mystr = ' he llo '
print(str.rstrip()) # he llo右邊的空格被删除
           

6. strip

删除兩斷的空⽩字元。

str = ' he llo '
print(str.strip()) #he llo           
8種字元串常見操作| 手把手教你入門Python之二十七
8種字元串常見操作| 手把手教你入門Python之二十七

字元串拼接

把參數進⾏周遊,取出參數⾥的每⼀項,然後再在後⾯加上mystr

S.join(iterable)
           

示例:

mystr = 'a'
print(mystr.join('hxmdq')) #haxamadaq 把hxmd⼀個個取出,并在後⾯添加字元a. 最後的 q 保
留,沒有加 a
print(mystr.join(['hi','hello','good'])) #hiahelloagood
           

作⽤:可以把清單或者元組快速的轉變成為字元串,并且以指定的字元分隔。

txt = '_'
print(txt.join(['hi','hello','good'])) #hi_hello_good
print(txt.join(('good','hi','hello'))) #good_hi_hello           

字元串運算符

  1. 字元串和字元串之間能夠使⽤加法運算符,作⽤是将兩個字元串拼接成為⼀個字元串。例

    如: 'hello' + 'world' 的結果是 'helloworld'

  2. 字元串和數字之間可以做乘法運算,結果是将指定的字元串重複多次。例如: 'hello'*2 的結果

    是 hellohello

  3. 字元串和字元串之間,如果使⽤⽐較運算符進⾏計算,會擷取字元對應的編碼,然後進⾏⽐較。
  4. 除上述⼏種運算符以外,字元串預設不⽀持其他運算符。
    8種字元串常見操作| 手把手教你入門Python之二十七