18個(gè) Python 字符串操作神技
大家好!今天咱們聊聊 Python 里的那些關(guān)于字符串操作的神乎其神的小技巧,讓我們的代碼變得更酷、更高效!準(zhǔn)備好你的筆記,讓我們一起探索吧!
1.切片大法好 - str[start:end]:就像切蛋糕一樣,截取字符串的一部分。比如,s = "Hello, World!", s[7:12] 就是 "World"。
2.反轉(zhuǎn)戲法 - str[::-1]:想要把字符串倒過來?沒問題,像這樣:s[::-1],例如 "hello" 變成 "olleh"。
3.計(jì)數(shù)器來了 - str.count(substring):統(tǒng)計(jì)子串出現(xiàn)的次數(shù),如 "abracadabra".count("a") 輸出 5。
4.替換魔術(shù) - str.replace(old, new):替換子串,比如 "hello world".replace("world", "Python") 就成了 "hello Python"。
5.首字母大寫 - str.capitalize():神奇的一鍵,首字母大寫,其他小寫,比如 "hello".capitalize() 是 "Hello"。
6.全大寫/小寫 - str.upper() 和 str.lower():分別轉(zhuǎn)換為大寫和小寫,比如 "Hello".upper() 得到 "HELLO"。
7.分割線 - str.split(separator):按指定字符分隔,比如 "one,two,three".split(",") 會返回 ["one", "two", "three"]。
8.連接符 - + 或 join():拼接字符串,"a" + "b" 或者 ",".join(["one", "two", "three"]) 都行。
9.去除空格 - str.strip():去掉兩邊的空白," hello ".strip() 結(jié)果是 "hello"。
10.去除首尾 - str.lstrip() 和 str.rstrip():只去首尾或尾部的空格。
11.格式化字符串 - f-string:用花括號 {} 包裹變量,如 name = "Alice" 時(shí),f"Hello, {name}!" 是 "Hello, Alice!"。
12.去除特殊字符 - str.translate():替換或刪除指定字符,如刪除所有標(biāo)點(diǎn)符號。
13.正則表達(dá)式 - re 模塊:高級字符串操作,比如查找所有數(shù)字 re.findall(r'\d+', "123abc456def")。
14.編碼解碼 - str.encode() 和 str.decode():處理文本編碼問題,如 "hello".encode('utf-8')。
15.字符串長度 - len(str):獲取字符串長度,len("Hello, World!") 是 13。
16.格式化輸出 - format() 方法:控制輸出格式,如 "{:.2f}".format(3.14159) 會顯示 "3.14"。
17.字符串拼接生成器 - 使用 *:" ".join(s * 3) 可以重復(fù)字符串三次,如 "abc"*3 輸出 "abcabcabc"。
18.判斷是否包含 - str.contains(substring) 或 in 關(guān)鍵字:檢查字符串是否包含子串,如 "Python" in "Hello, Python!" 返回 True。
這些小技巧不僅實(shí)用,而且能讓你的Python代碼看起來既優(yōu)雅又強(qiáng)大。記得多多練習(xí),熟練掌握它們,你的代碼將會更加得心應(yīng)手!加油,碼出你的優(yōu)雅人生!