Python 字串方法(String Methods)大全,這是學習 Python 字串操作的基礎核心工具。
1. capitalize()
將第一個字母轉為大寫,其餘轉小寫:txt = "hello world"
print(txt.capitalize())
輸出:
Hello world2. lower() / upper() / swapcase()
print("Hello".lower()) # hello
print("hello".upper()) # HELLO
print("Hello".swapcase()) # hELLO
3. count()
統計某子字串出現的次數:
txt = "banana"
print(txt.count("a"))
輸出:
34. find() / rfind() / index()
尋找子字串的 位置(找不到時 find() 回傳 -1,index() 會報錯):
index()基本語法
string.index(substring, start, end)
- substring要搜尋的子字串
- start(選填)起始搜尋位置
- end(選填)結束搜尋位置(不包含此位置)
EX1 :find() / rfind()
txt = "hello world"
print(txt.find("o")) # 4
print(txt.rfind("o")) # 7
EX2 : index()
txt = "hello world"
pos = txt.index("o")
print(pos)
輸出:
4EX3 :
txt = "hello hello"
pos = txt.index("o", 5)
print(pos)
輸出:
105. startswith() / endswith()
檢查字串開頭或結尾是否為指定內容:
txt = "Hello World"
print(txt.startswith("Hello")) # True
print(txt.endswith("World")) # True
6. strip() / lstrip() / rstrip()
去除前後(或左/右)空白或特定字符:
txt = "xxxhelloxxx"
print(txt.strip("x")) # "xxxhelloxxx"
print(txt.lstrip("x")) # "helloxxx"
print(txt.rstrip("x")) # "xxxhello"
7. replace()
取代子字串:
txt = "I love cats"
print(txt.replace("cats", "dogs"))
輸出:
I love dogs
8. split() / rsplit() / splitlines()
分割字串成清單:
.splitlines() 是一個 字串方法,它的功能是:
➜ 將整個字串按照換行符(\n)或其他換行符號切開,回傳一個列表(list)
txt = "apple,banana,cherry"
print(txt.split(",")) # ['apple', 'banana', 'cherry']
lines = "A\nB\nC"
print(lines.splitlines()) # ['A', 'B', 'C']
9. join()
將清單用某符號串接成字串:
words = ["apple", "banana", "cherry"]
print(", ".join(words))
輸出:
apple, banana, cherry
10. zfill()
將字串補零至固定長度:
print("42".zfill(5)) # 00042





















