31個必備的Python字串方法,建議收藏!
字串是Python中基本的資料類型,幾乎在每個Python程式中都會使用到它。
1、Slicing
slicing切片,依照一定條件從清單或元組中取出部分元素(例如特定範圍、索引、分割值)
s = ' hello ' s = s[:] print(s) #hello s = ' hello ' s = s[3:8] print(s) # hello
2、strip ()
strip()方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字元序列。
s = ' hello '.strip() print(s) # hello s = '###hello###'.strip() print(s) # ###hello###
在使用strip()方法時,預設會移除空格或換行符,所以#號並沒有移除。
可以為strip()方法新增指定字符,如下所示。
s = '###hello###'.strip('#') print(s) # hello
此外當指定內容不在頭尾處時,並不會被移除。
s = ' n t hellon'.strip('n') print(s) # #hello s = 'n t hellon'.strip('n') print(s) #hello
第一個n前面有個空格,所以只會去取尾部的換行符。
最後strip()方法的參數是剝離其值的所有組合,這可以看下面這個案例。
s = 'www.baidu.com'.strip('cmow.') print(s) # baidu
最外層的首字和尾字參數值將從字串中剝離。字元從前端移除,直到到達一個不包含在字元集中的字串字元為止。
在尾部也會發生類似的動作。
3、lstrip()
移除字串左側指定的字元(預設為空格或換行符)或字元序列。
s = ' hello '.lstrip() print(s) # hello
同樣的,可以移除左側所有包含在字元集中的字串。
s = 'Arthur: three!'.lstrip('Arthur: ') print(s) # ee!
4、rstrip()
移除字串右側指定的字元(預設為空格或換行符)或字元序列。
s = ' hello '.rstrip() print(s) #hello
5、removeprefix()
Python3.9中移除前綴的函數。
# python 3.9 s = 'Arthur: three!'.removeprefix('Arthur: ') print(s) # three!
和strip()相比,不會把字元集中的字串逐一匹配。
6、removesuffix()
Python3.9中移除後綴的函數。
s = 'HelloPython'.removesuffix('Python') print(s) # Hello
7、replace()
把字串中的內容替換成指定的內容。
s = 'string methods in python'.replace(' ', '-') print(s) # string-methods-in-python s = 'string methods in python'.replace(' ', '') print(s) # stringmethodsinpython
8、re.sub()
re是正規的表達式,sub是substitute表示替換。
re.sub則是相對複雜點的替換。
import re s = "stringmethods in python" s2 = s.replace(' ', '-') print(s2) # string----methods-in-python s = "stringmethods in python" s2 = re.sub("s+", "-", s) print(s2) # string-methods-in-python
和replace()做對比,使用re.sub()進行替換操作,確實更高階點。
9、split()
對字串做分隔處理,最終的結果就是一個列表。
s = 'string methods in python'.split() print(s) # ['string', 'methods', 'in', 'python']
當不指定分隔符號時,預設會以空格分隔。
s = 'string methods in python'.split(',') print(s) # ['string methods in python']
此外,也可以指定字串的分隔次數。
s = 'string methods in python'.split(' ', maxsplit=1) print(s) # ['string', 'methods in python']
10、rsplit()
從右側開始將字串分隔。
s = 'string methods in python'.rsplit(' ', maxsplit=1) print(s) # ['string methods in', 'python']
11、join()
string.join(seq)。以string作為分隔符,將seq中所有的元素(的字串表示)合併為一個新的字串。
list_of_strings = ['string', 'methods', 'in', 'python'] s = '-'.join(list_of_strings) print(s) # string-methods-in-python list_of_strings = ['string', 'methods', 'in', 'python'] s = ' '.join(list_of_strings) print(s) # string methods in python
12、upper()
將字串中的字母,全部轉換為大寫。
s = 'simple is better than complex'.upper() print(s) # SIMPLE IS BETTER THAN COMPLEX
13、lower()
將字串中的字母,全部轉換為小寫。
s = 'SIMPLE IS BETTER THAN COMPLEX'.lower() print(s) # simple is better than complex
14、capitalize()
將字串中的首個字母轉換為大寫。
s = 'simple is better than complex'.capitalize() print(s) # Simple is better than complex
15、islower()
判斷字串中的所有字母是否都為小寫,是則傳回True,否則傳回False。
print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False print('simple is better than complex'.islower()) # True
16、isupper()
判斷字串中的所有字母是否都為大寫,是則傳回True,否則傳回False。
print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True print('SIMPLE IS BETTER THAN complex'.isupper()) # False
17、isalpha()
如果字串至少有一個字元且所有字元都是字母,則傳回 True,否則傳回 False。
s = 'python' print(s.isalpha()) # True s = '123' print(s.isalpha()) # False s = 'python123' print(s.isalpha()) # False s = 'python-123' print(s.isalpha()) # False
18、isnumeric()
如果字串中只包含數字字符,則傳回 True,否則傳回 False。
s = 'python' print(s.isnumeric()) # False s = '123' print(s.isnumeric()) # True s = 'python123' print(s.isnumeric()) # False s = 'python-123' print(s.isnumeric()) # False
19、isalnum()
如果字串中至少有一個字元且所有字元都是字母或數字,則傳回True,否則傳回 False。
s = 'python' print(s.isalnum()) # True s = '123' print(s.isalnum()) # True s = 'python123' print(s.isalnum()) # True s = 'python-123' print(s.isalnum()) # False
20、count()
傳回指定內容在字串中出現的次數。
n = 'hello world'.count('o') print(n) # 2 n = 'hello world'.count('oo') print(n) # 0
21、find()
偵測指定內容是否包含在字串中,如果是傳回開始的索引值,否則傳回-1。
s = 'Machine Learning' idx = s.find('a') print(idx) print(s[idx:]) # 1 # achine Learning s = 'Machine Learning' idx = s.find('aa') print(idx) print(s[idx:]) # -1 # g
此外,也可以指定開始的範圍。
s = 'Machine Learning' idx = s.find('a', 2) print(idx) print(s[idx:]) # 10 # arning
22、rfind()
類似於find()函數,傳回字串最後一次出現的位置,如果沒有符合項目則傳回 -1。
s = 'Machine Learning' idx = s.rfind('a') print(idx) print(s[idx:]) # 10 # arning
23、startswith()
檢查字串是否是以指定內容開頭,是則傳回 True,否則傳回 False。
print('Patrick'.startswith('P')) # True
24、endswith()
檢查字串是否以指定內容結束,是則傳回 True,否則傳回 False。
print('Patrick'.endswith('ck')) # True
25、partition()
string.partition(str),有點像是find()和split()的結合體。
從str出現的第一個位置起,把字串string分成一個3 元素的元組(string_pre_str,str,string_post_str),如果string中不包含str則 string_pre_str==string。
s = 'Python is awesome!' parts = s.partition('is') print(parts) # ('Python ', 'is', ' awesome!') s = 'Python is awesome!' parts = s.partition('was') print(parts) # ('Python is awesome!', '', '')
26、center()
傳回一個原始字串居中,並使用空格填入長度width的新字串。
s = 'Python is awesome!' s = s.center(30, '-') print(s) # ------Python is awesome!------
27、ljust()
傳回一個原始字串左對齊,並使用空格填入長度width的新字串。
s = 'Python is awesome!' s = s.ljust(30, '-') print(s) # Python is awesome!------------
28、rjust()
傳回一個原始字串右對齊,並使用空格填入長度width的新字串。
s = 'Python is awesome!' s = s.rjust(30, '-') print(s) # ------------Python is awesome!
29、f-Strings
f-string是格式化字串的新語法。
与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!
num = 1 language = 'Python' s = f'{language} is the number {num} in programming!' print(s) # Python is the number 1 in programming! num = 1 language = 'Python' s = f'{language} is the number {num*8} in programming!' print(s) # Python is the number 8 in programming!
30、swapcase()
翻转字符串中的字母大小写。
s = 'HELLO world' s = s.swapcase() print(s) # hello WORLD
31、zfill()
string.zfill(width)。
返回长度为width的字符串,原字符串string右对齐,前面填充0。
s = '42'.zfill(5) print(s) # 00042 s = '-42'.zfill(5) print(s) # -0042 s = '+42'.zfill(5) print(s) # +0042
以上是31個必備的Python字串方法,建議收藏!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。
