Python學習之字符串常用方法總結

接下來我們會進入 字符串常用方法的應用階段,重點學習字符串的內置函數。正式學習之前,我們要先瞭解一個詞 對象 (劃重點,不是男女朋友!),隻有知道 對象是什麼?才能更好的幫助我們接下來的學習。

什麼是對象

對於 Python 來說,對象的概念,更像是身份的概念,我們可以理解為 每一個 變量 其實就是 對象。

  • Python 中一切皆是對象
  • 每個對象都有自己的屬性和方法
  • 對象的特點就是它的屬性,它的功能就是它的方法,也可以說是函數。比如字符串就有很多內置函數來幫助我們處理字符串。

Python 萬物皆是對象

Python裡面有一句話:萬物解釋對象

在編程領域中,通常把現實世界中的實體稱為對象,例如:

  • 香蕉、蘋果、橘子
  • 男人、女人、小孩
  • 飛機、地鐵、突突車
  • 平房、樓房、小別墅

對象指的是一個具體的實體,不用於指代一個抽象的群體(或者也可以說是一個實體所處的群體)

  • 香蕉是一個具體的水果,所以可以說香蕉是一個對象
  • 它是一種水果,但水果是一個抽象的概念,指的是一群可食用的含水分和糖分較多的植物果實
  • 你可以說,香蕉、蘋果、橘子是水果,但是不能說水果就隻能是香蕉、隻能是蘋果、隻能是橘子…
  • 所以不能說水果是一個對象

類似的,飛機、地鐵這些具體的交通工具可以被稱為對象,但是不能說交通工具是一個對象

字符串的索引

學習字符串的常用方法之前,我們再來吻戲一下字符串的索引

索引[]

通過索引 [] 獲取字符串中指定位置的字符,示例如下:

>>> s = 'Python'
>>> s[0]
'P'
>>> s[1]
'y'
>>> s[2]
't'
>>> s[3]
'h'
>>> s[4]
'0'
>>> s[5]
'n'
  • 在 Python 中,單個字符也被當作字符串來處理,即該字符串隻包含一個字符
  • 在第 2 行,獲取字符串 s 的第 0 個字符 ‘P’
  • 在第 4 行,獲取字符串 s 的第 1 個字符 ‘y’
  • 在第 6 行,獲取字符串 s 的第 1 個字符 ‘t’
  • 在第 8 行,獲取字符串 s 的第 1 個字符 ‘h’
  • 在第 10 行,獲取字符串 s 的第 1 個字符 ‘o’
  • 在第 12 行,獲取字符串 s 的第 1 個字符 ‘n’

索引[:]

在 Python 中,使用語法 string [start:end],獲取字符串 string 中在 [start, end) 范圍的子字符串。

註意范圍 [start, end) 包含 start,不包含 end。也可以理解為是列表的 左閉右開原則 。

舉例如下:

>>> s = 'Python'
>>> s[1]
'y'
>>> s[2]
't'
>>> s[3]
'h'
>>> s[0:5]
'Pytho'
  • 在第 2 行,獲取字符串 s 的第 1 個字符 ‘m’
  • 在第 4 行,獲取字符串 s 的第 2 個字符 ‘o’
  • 在第 6 行,獲取字符串 s 的第 3 個字符 ‘o’
  • 在第 8 行,獲取字符串 s 中從 1 開始、到 4 結束的字符串 ‘mooc’,使用 s [1:4] 表示該范圍,註意該范圍包括字符串的第 1 個字符、不包括第 4 個字符。

字符串的常用方法

find()函數 與 index()函數

find() 函數與 index() 函數的功能:都是返回你想找的成員(元素)的位置

find() 函數的用法:str = string.finde(item) item:想要查詢匹配的元素,返回一個整型

index() 函數的用法:str = string.index(item) item:想要查詢匹配的元素,返回一個整型或者報錯

附:字符串裡的位置是從左向右從下標位[0]開始計算

find() 函數與 index() 函數的區別:

  • 如果 find() 函數 找不到c成員(元素),會返回 -1
  • 如果 index()函數 找不到成員(元素),會導致程序報錯
info = "Python is good code"

print(info.find("P"))
print(info.find("good"))
print(info.find("Java"))

# >>> 0
# >>> 10
# >>> -1
info = "Python is good code"

print(info.index("P"))
print(info.index("good"))
print(info.index("Java"))	# 直接報錯(語法錯誤) 'ValueError: substring not found'

# >>> 0
# >>> 10

startswith() 函數與 endswith() 函數

startswith() 函數的功能:判斷字符串 開始位 是否是某成員(元素),可以指定統計的范圍,[start,end) 左閉區間右開區間

startswith() 函數的用法:str = string.startswith(item) item:想要查詢匹配的元素,返回一個佈爾值

endswith() 函數的功能:判斷字符串 結尾 是否是某成員(元素),可以指定統計的范圍,[start,end) 左閉區間右開區間

startswith() 函數的用法:str = string.endswith(item) item:想要查詢匹配的元素,返回一個佈爾值

示例如下:

info = 'Python is good'

print(info.startswith('Python'))
print(info.startswith('Java'))
print(info.endswith('good'))
print(info.endswith('bad'))

# >>> True
# >>> False
# >>> True
# >>> False

string_test = "this is string example"
print(string_test.startswith('this'))           # 字符串是否以 this 開頭
print(string_test.startswith('string', 8))      # 從第九個字符開始的字符串是否以 string 開頭
print(string_test.startswith('this', 2, 4))     # 從第2個字符開始到第四個字符結束的字符串是否以 this 開頭

# >>> True
# >>> True
# >>> False

capitalize () 函數

capitalize 的功能 : 將字符串的首字母大寫

capitalize 的用法:str = string.capitalize() ;

示例如下:

>>> str = 'string'
>>> str.capitalize()
'String'

capitalize() 的註意事項:

  • 隻對首字母有效
  • 隻對字母有效
  • 已經是大寫,則無效

capitalize()函數小練習

將han meimei轉換成規范的英文名字,打印實現姓、名首字母都是大寫

name_1="han"
name_2="meimei"

print(name_1.capitalize() + ' ' +name_2.capitalize())
# >>> 輸出結果 'Han Meimei'

casefold()函數與lower()函數

casefold()函數與lower()函數 的功能 : 將字符串的全體字符小寫

casefold()函數與lower()函數 的用法:str = string.casefold() , str = string.lower() ;

示例如下:

>>> str_01 = 'Hello'
>>> str_01.casefold()
'hello'

>>> str_02 = 'World'
>>> str_02.lower()
'world'

casefold()函數與lower()函數 的註意事項:

  • 隻對字符串的字母有效
  • 已經是小寫的字母無效
chinese = "你好,世界"
english = "Hello,World"
test_str = "[email protected]$OK"

print(chinese.casefold())
print(chinese.lower())
print(english.casefold())
print(english.lower())
print(test_str.casefold())
print(test_str.lower())

既然 casefold()函數與lower()函數 都可以將字符串的全體字符轉為小寫,那麼又有什麼區別呢?

其實還是有區別的,lower()函數是很早之前就存在的將字符串小寫的方法,而casefold()函數則是 Python3.3版本之後才引入的小寫方法。lower()函數是將英文字符進行小寫,但是對德語等其他非英語字符就失去瞭效果,這個時候就是 casefold() 函數大顯身手的時候瞭。

casefold()函數與lower()函數 小練習

將下列三個驗證碼全部轉為 小寫

str_1 = “NAh8”

str_2 = “Sn6H”

str_3 = “HKFM”

str_1 = "NAh8"
str_2 = "Sn6H"
str_3 = "HKFM"

print (str_1.lower())
print (str_2.casefold())
print (str_3.lower())

upper() 函數

upper() 函數的功能:將字符串全體大寫

upper() 函數的用法:str = string.upper()

示例如下:

>>> str = 'string'
>>> str.upper()
'STRING'

capitalize 的註意事項:

  • 隻對字符串的字母有效
  • 已經是大寫的字母無效
str_test = 'Hello World'
print(str_test.upper())
# >>> 'HELLO WORLD'

swapcase() 函數

swapcase() 函數的功能:將字符串中的字符進行大小寫轉換

swapcase() 函數的用法:str = string.swapcase()

swapcase() 函數的註意事項:隻對字符串的字母有效

info_one = 'Python is good'
info_two = 'pthon web is so esay'

print(info_one.swapcase())
print(info_two.swapcase())

zfill() 函數

zfill() 函數的功能:為字符串定義長度,如果現有字符串長度不滿足,缺少的部分自動用 0 補齊

zfill() 函數的用法:str = string.zfill(width) width:新字符串希望的長度

zfill() 函數的註意事項:與字符串的字符沒有關系;如果定義的字符串長度小於當前字符串長度,則不會發生變化。

info = "Hello World"

print(info.zfill(10))
print(info.zfill(15))
print(info.zfill(20))

count() 函數

count() 函數的功能:統計字符串出現的次數;或者說返回當前字符串某個成員(元素)出現的次數

count() 函數的用法:str = string.zfill(item) item:查詢個數/次數的元素

count() 函數的註意事項:如果查詢的成員(元素)不存在,則返回 0

info = '''
        Please send this message to those people who mean something to you,to those who have touched your life in 	
        one way or another,to those who make you smile when you really need it,to those that make you see the 
        brighter side of things when you are really down,to those who you want to let them know that you appreciate 
        their friendship. And if you don't, don't worry,nothing bad will happen to you,you will just miss out on the 
        opportunity to brighten someone's day with this message.

        '''
this_count = info.count('this')
you_count = info.count('you')
love_count = info.count('love')

print('"this"出現的次數為: ' + str(this_count) + '次')
# >>> "this"出現的次數為: 2次
print('"you"出現的次數為: ' + str(you_count) + '次')
# >>> "you"出現的次數為: 11次
print('"love"出現的次數為: ' + str(love_count) + '次')
# >>> "maybe"出現的次數為: 0次

strip()函數

strip() 函數的功能 :去掉字符串兩邊的指定元素,默認是空格

strip() 函數的用法 :str = string.strip(item) ,括弧裡傳一個想要去掉的成員(元素),可以不填寫

strip() 函數的拓展 :

  • 傳入的元素如果不在開頭或者結尾則無效
  • lstrip 僅去掉字符串開頭的指定元素或者是空格
  • rstrip 僅去掉字符串結尾的指定元素或者是空格

示例如下:

info = '    Jack is a good boy    '
new_info_01 = info.strip()

print(new_info_01)

# >>> Jack is a good boy

new_info_02 = info.strip(info)
print(new_info_02)
print(len(new_info_02))

# >>>          實際上這裡的 'new_info_02' 已經北清空瞭
# >>> 0        清空後的 'new_info_02' 長度為0

text = 'abcde'
text_lstrip = text.lstrip('a')
print(text_lstrip)

# >>> bcde

text_rstrip = text.rstrip('e')
print(text_rstrip)

# >>> abcd

replace()函數

replace()函數的功能:把字符串中的 old(舊字符串) 替換成 new(新字符串),並可以指定數量,默認 -1 代表替換全部

replace()函數的用法:str = string.replace(old, new, max)

  • old :被替換的元素
  • new:替換 old 的元素
  • max:可選,代表替換幾個,默認替換掉全部匹配到的 old 。

示例如下:

info = "hello, Neo"

print(info.replace("Neo", "Jack"))
print(info.replace(" ", "*", 1))
# >>> hello, Jack
# >>> hello,*Neo

info_test = "hello world !!!"
new_info_01 = info_test.replace("h", "H")
new_info_02 = new_info_01.replace("w", "W")

print(new_info_02.replace('!!!', 'Python'))
# >>> Hello World Python

join() 函數

join()函數的功能:將序列中的元素以指定的字符連接生成一個新的字符串

join()函數的用法:str = "".join(lists)

示例如下:

lists = ["a", "b", "c"]
tuples = ("1", "2", "3")

print("*".join(lists))        # >>> a*b*c
print("@".join(tuples))        # >>> 1@2@3

知識點

“”.join(lists) 是常見的將列表、元組轉成字符串的寫法

列表裡面隻能存放字符串元素,有其他類型的元素會報錯 TypeError: sequence item 0: expected str instance, int found

元組也能傳進去

split() 函數

split()函數的功能:將字符串按照str分割成列表,如果參數 num 有指定值,則分隔 num+1 個子字符串

split()函數的用法:str = string.split() ,括號內可以指定分隔符

使用空格將字符串分割為多個單詞,返回一個列表,示例如下:

info = 'Hello World Python Is Good'

print(info.split(" "))			# >>> ['Hello', 'World', 'Python', 'Is', 'Good']
print(info.split(" ", 1))		# >>> ['Hello', 'World Python Is Good']

缺省情況下,使用空格將字符串分割為多個單詞,可以在 split () 方法中指定分隔符,示例如下:

info = 'Hello World:Python Is_Good'

print(info.split(":"))		# >>> ['Hello World', 'Python Is_Good']

字符串中返回 bool 類型的函數集合

之所以說它是集合,是因為我們有多個函數返回的是 bool 類型,接下來我們看看都有哪些函數返回的是 bool 類型。

isspace() 函數

isspace() 函數的功能:判斷字符串是否是一個由空格組成的字符串

isspace() 函數的用法:isspace_bool_type = string.isspace() ,無參數可傳,返回一個 bool 類型

示例如下:

string = ' '
print(string.isspace())
# >>> True

new_string = 'hello world'
print(new_string.isspace())
# >>> False		雖然 'hello world' 中有一個空格,但是除瞭空格之外,還有其他字符,所以返回 False

附:這裡需要註意一點,由空格組成的字符串不等於空字符串,因為空格也占用一個長度。

istitle() 函數

istitle()函數的功能:判斷字符串是否是一個標題類型 (即多個單詞,首字母都是大寫)

istitle()函數的用法:istitle_bool_type = string.istitle() ,無參數可傳,返回一個 bool 類型

示例如下:

info_01 = 'Hello Jack'
info_02 = 'hello jack'

print(info_01.istitle())    # >>> True
print(info_02.istitle())    # >>> False

附:需要註意的是該函數隻能對英文有效

isupper() 函數 與 islower() 函數

功能:

  • isupper() 函數 判斷字符串中的字符是否都是大寫
  • islower() 函數 判斷字符串中的字符是否都是小寫

用法:

  • isupper_bool_type = string.isupper() ,無參數可傳,返回一個 bool 類型
  • islower_bool_type = islower(),無參數可傳,返回一個 bool 類型

示例如下:

text_01 = 'GOOD BYE'

print(text_01.isupper())    # >>> True
print(text_01.islower())    # >>> False

以上就是Python學習之字符串常用方法總結的詳細內容,更多關於Python字符串的資料請關註WalkonNet其它相關文章!

推薦閱讀: