『無為則無心』Python序列 — 17、Python字符串操作常用API
- 2021 年 7 月 2 日
- 筆記
- 測試基礎必會技能 - Python基礎
上一篇文章說了Python字符串下標和切片的概念,這篇文章來說說Python中對字符串的常用操作。
對字符串的操作主要分為三大類:查找、修改和判斷。
1、字符串的查找
所謂字符串查找方法,即是查找一個子串在字符串中的位置或出現的次數。
@1、find()
方法
find()
方法是,檢測某個子串是否包含在這個字符串中,如果存在返回這個子串開始位置的下標,否則則返回-1
。
1)語法:
字符串序列.find(子串, 開始查找的位置下標, 結束查找的位置下標)
注意:開始和結束位置下標可以省略,表示在整個字符串序列中查找。
2)快速體驗:
mystr = "Life is short,you need Python。"
print(mystr.find('short')) # 8
# 在字符串標記的範圍內查找
print(mystr.find('o', 13, 25)) # 15
print(mystr.find('hello')) # -1
@2、index()
方法
index()
方法檢測某個子串是否包含在這個字符串中,如果存在返回這個子串開始的位置下標,否則則報異常。
index()
方法獲取指定元素在列表中的第一次出現時索引,如果一個字符串內出現多處子串存在,返回第一個子串開始的位置下標。
1)語法:
字符串序列.index(子串, 開始查找的位置下標, 結束查找的位置下標)
注意:開始和結束位置下標可以省略,表示在整個字符串序列中查找。
2)快速體驗:
mystr = "Life is short,you need Python。"
print(mystr.find('short')) # 8
# 在字符串標記的範圍內查找
# 可以只寫開始位置
print(mystr.find('o', 13, 25)) # 15
# 報錯ValueError: substring not found
print(mystr.find('hello'))
@3、rfind()
和rindex()
方法
rfind()
方法: 和find()
方法功能相同,但查找方向為右側開始。rindex()
方法:和index()
方法功能相同,但查找方向為右側開始。
注意:但是下標還是從左到右,從0開始算起,只是查找開始的方向不同。
@4、count()
方法
count()
方法:返回某個子串在字符串中出現的次數。
1)語法:
字符串序列.count(子串, 開始位置下標, 結束位置下標)
注意:開始和結束位置下標可以省略,表示在整個字符串序列中查找。
2)快速體驗:
mystr = "Life is short,you need Python。"
print(mystr.count('o')) # 3
# 在字符串標記的範圍內查找
# 可以只寫開始位置
print(mystr.count('o', 13, 25)) # 1
print(mystr.count('hello')) # 0
2、字符串的修改
所謂修改字符串,指的就是通過函數的形式修改字符串中的數據。(字符串修改的方法很多,我們只講解一下最常用的。)
@1、replace()
方法
replace()
:替換
1)語法:
字符串序列.replace(舊子串, 新子串, 替換次數)
注意:替換次數如果查出子串出現次數,則替換次數為該子串出現次數。
2)快速體驗:
mystr = "hello and String and python and world"
# 1.把字符串中的and全部換成he,查出幾次,替換幾次。
# 結果:hello he String he python he world
new_str = mystr.replace('and', 'he')
print(new_str)
# 2。替換次數如果超出子串出現的次數,表示替換所有子串
# 結果:hello he String he python he world
new_str = mystr.replace('and', 'he', 10)
print(new_str)
# 3、查出的子串中,只替換前兩個
# 結果:hello he String he Python and world
new_str = mystr.replace('and', 'he', 2)
print(new_str)
3)注意(重要)
調用了replace()
方法後,發現原有字符串的數據並沒有做到修改,修改後的數據是replace()
方法的返回值,說明字符串是不可變數據類型。
同時也說明:說明replace()
方法有返回值,返回值是修改後的字符串。
應該所有關於字符串修改的函數,都有返回值,且返回修改後的字符串。
總結:數據按照是否能直接修改分為可變類型數據和不可變類型數據兩種。字符串類型的數據修改的時候不能改變原有字符串,屬於不能直接修改數據的類型即是不可變類型。
@2、split()
方法
split()
方法:按照指定字符分割字符串。返回一個列表,並丟失字符串中包含的分割字符。
1)語法:
字符串序列.split(分割字符, num)
注意:
num
表示的是分割字符出現的次數,即將來返回數據個數為num+1
個。
2)快速體驗:
mystr = "hello and String and python and world"
# 1.以and為分割符,分割字符串,出現的分割全部分割。
# 結果:['hello ', ' String ', ' python ', ' world']
new_str = mystr.split('and')
print(new_str)
# 2.只把前兩次出現的分割符,進行字符串的分割
# 結果:['hello ', ' String ', ' python and world']
new_str = mystr.split('and', 2)
print(new_str)
注意:如果分割字符是原有字符串中的子串,分割後則丟失該子串。
@3、join()
方法
join()
方法:用一個字符或子串合併字符串,即將多個字符串合併為一個新的字符串。
1)語法:
字符或子串.join(多字符串組成的序列)
2)快速體驗:
# 合併列表裏面的字符串為一個大的字符串
# 結果:aa...bb...cc
mylist = ['aa', 'bb', 'cc']
print('...'.join(mylist))
# 結果:hello world hello python
list1 = ['hello', 'world', 'hello', 'python']
print(' '.join(list1))
@4、capitalize()
方法
capitalize()
方法:將字符串第一個字符轉換成大寫。
代碼演示如下:
"""
下面結果可以看到兩點
1.字符串的第一個字符變成大寫了。
2.除了首字符外,其他字符如有大寫,都變成小寫。
"""
# 結果:Life is short,you need python。
mystr = "life is short,you need Python。"
new_str = mystr.capitalize()
print(new_str)
注意:
capitalize()
方法轉換後,隻字符串第一個字符大寫,其他的字符全都小寫。
@5、title()
方法
title()
方法:將字符串每個單詞首字母轉換成大寫。
代碼演示如下:
# 將字符串中的每個單詞的首字母都轉換成大寫。
# 如果單詞的首字母原本就是大寫,保持不變。
# 結果:Life Is Short,You Need Python。
mystr = "life is short,you need Python。"
new_str = mystr.title()
print(new_str)
@6、lower()
方法
lower()
方法:將字符串中大寫轉小寫。
代碼演示如下:
# 把字符串變成全小寫。
# 結果:life is short,you need python。
mystr = "life is short,You Need Python。"
new_str = mystr.lower()
print(new_str)
@7、upper()
方法
upper()
方法:將字符串中小寫轉大寫。
代碼演示如下:
# 把字符串變成全大寫。
# 結果:LIFE IS SHORT,YOU NEED PYTHON。
mystr = "life is short,You Need Python。"
new_str = mystr.upper()
print(new_str)
@8、lstrip()
方法
lstrip()
方法:刪除字符串左側空白字符。
代碼演示如下:
# 結果:"Life is short,you need Python。 "
mystr = " Life is short,you need Python。 "
new_str = mystr.lstrip()
print(new_str)
@9、rstrip()
方法
rstrip()
方法:刪除字符串右側空白字符。
代碼演示如下:
# 結果:" Life is short,you need Python。"
mystr = " Life is short,you need Python。 "
new_str = mystr.rstrip()
print(new_str)
@10、strip()
方法
strip()
方法:刪除字符串兩側空白字符。
代碼演示如下:
# 結果:"Life is short,you need Python。"
mystr = " Life is short,you need Python。 "
new_str = mystr.strip()
print(new_str)
@11、ljust()
方法
ljust()
方法:返回一個原字符串左對齊的字符串,並使用指定字符(默認空格)填充至對應長度的新字符串。
1)語法:
字符串序列.ljust(長度, 填充字符)
2)示例:
# 輸出結果:Pyhton....
mystr = "Pyhton"
new_str = mystr.ljust(10 , ".")
print(new_str)
@12、rjust()
方法
rjust()
方法:返回一個原字符串右對齊的字符串,並使用指定字符(默認空格)填充至對應長度的新字符串。
語法和ljust()
方法相同。
代碼演示如下:
# 字符串序列.rjust(長度, 填充字符)
# 輸出結果:....Pyhton
mystr = "Pyhton"
new_str = mystr.rjust(10 , ".")
print(new_str)
@13、center()
方法
center()
方法:返回一個原字符串居中對齊的字符串,並使用指定字符(默認空格)填充至對應長度的新字符串。
語法和ljust()
方法相同。
代碼演示如下:
# 字符串序列.center(長度, 填充字符)
# 輸出結果:..Pyhton..
mystr = "Pyhton"
new_str = mystr.center(10 , ".")
print(new_str)
"""
有的時候可能不是絕對居中,
補充字符數可能是奇數,
調整長度即可讓補充字符數變成偶數,
來達到絕對居中效果。
"""
3、字符串的判斷
所謂判斷即是判斷真假,返回的結果是布爾型數據類型:True 或 False。
@1、startswith()
方法
startswith()
方法:檢查字符串是否是以指定子串開頭,是則返回 True,否則返回 False。如果設置開始和結束位置下標,則在指定範圍內檢查。
1)語法:
字符串序列.startswith(子串, 開始位置下標, 結束位置下標)
開始位置下標和結束位置下標可以不寫,不寫則是全字符串內檢查。
2)快速體驗:
mystr = "Life is short,you need Python"
# 結果:True
new_str = mystr.startswith('Li')
print(new_str)
# 結果False
mystr = "Life is short,you need Python"
new_str = mystr.startswith('Li', 3, 15)
print(new_str)
@2、endswith()
方法
endswith()
方法:檢查字符串是否是以指定子串結尾,是則返回 True,否則返回 False。如果設置開始和結束位置下標,則在指定範圍內檢查。
1)語法:
字符串序列.endswith(子串, 開始位置下標, 結束位置下標)
開始位置下標和結束位置下標可以不寫,不寫則是全字符串內檢查。
2)快速體驗:
mystr = "Life is short,you need Python"
# 結果:False
new_str = mystr.endswith('thons')
print(new_str)
# 結果:False
new_str = mystr.endswith('thon', 5, 20)
print(new_str)
@3、isalpha()
方法
isalpha()
方法:如果字符串至少有一個字符,並且所有字符都是字母則返回 True, 否則返回 False。
代碼演示如下:
mystr = "Life is short,you need Python"
mystr1 = 'hello'
mystr2 = 'hello12345'
# 結果:False 因為有空格
new_str = mystr.isalpha()
print(new_str)
# 結果:True
new_str = mystr1.isalpha()
print(new_str)
# 結果:False 因為有數字
new_str = mystr2.isalpha()
print(new_str)
@4、isdigit()
方法
isdigit()
方法:如果字符串只包含數字則返回 True,否則返回 False。
代碼演示如下:
mystr = "12345 12345"
mystr1 = 'aaa12345'
mystr2 = '12345'
# 結果: False 因為有空格
new_str = mystr.isdigit()
print(new_str)
# 結果:False 因為有字母
new_str = mystr1.isdigit()
print(new_str)
# 結果:True
new_str = mystr2.isdigit()
print(new_str)
@5、isalnum()
方法
isalnum()
方法:如果字符串至少有一個字符,並且所有字符都是字母或數字或者字母和數字的組合,則返回 True,否則返回False。
代碼演示如下:
mystr = "Life is short,you need Python"
mystr1 = 'aaa12345'
mystr2 = '12345-'
# 結果:False 因為有空格
new_str = mystr.isalnum()
print(new_str)
# 結果:True
new_str = mystr1.isalnum()
print(new_str)
# 結果:False 只能是數字或者字母,其他字符都不行
new_str = mystr1.isalnum()
print(new_str)
@6、isspace()
方法
isspace()
方法:如果字符串中只包含空白,則返回True,否則返回False。
代碼演示如下:
mystr = "Life is short,you need Python"
mystr1 = ' '
# 結果:False
new_str = mystr.isspace()
print(new_str)
# 結果:True
new_str = mystr1.isspace()
print(new_str)
4、補充:Python中方法和函數的區別。
這裡簡單的說一說方法和函數,在Python3中,對方法和函數有明確的規定:
- 函數
function
:
A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body.
從定義的角度上看,我們知道函數(function
)就相當於一個數學公式,它理論上不與其它東西關係,它只需要相關的參數就可以。 - 方法
method
:
A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self).
那麼方法的意思就很明確了,它是與某個對象相互關聯的,也就是說它的實現與某個對象有關聯關係。這就是方法。雖然它的定義方式和函數是一樣的。也就是說,在Class定義的函數就是方法。(我的理解) - 總結:在Python3中方法和函數基本上是一樣。
只不過方法必須通過對象.方法()
的形式調用,如xxx.print()
方法實際上就是和對象關係緊密的函數。
而函數可以直接使用,如print()
。
(就先這樣理解,以後學習到函數的時候在詳細說明,這和Java還是有區別的。)