以下是 Python 常用字符串處理函數與方法的分類匯總,涵蓋基礎操作、格式化、查找替換、編碼轉換等核心場景,附示例說明:
一、基礎操作
1. 字符串拚接與分割
+
或+=
s = "Hello" + " " + "World" # "Hello World"
join(iterable)
words = ["Python", "is", "awesome"] s = " ".join(words) # "Python is awesome"
split(sep=None, maxsplit=-1)
s = "a,b,c".split(",") # ["a", "b", "c"]
splitlines([keepends=False])
lines = "Line1\nLine2\r\nLine3".splitlines() # ["Line1", "Line2", "Line3"]
2. 大小寫轉換
upper()
/lower()
"Hello".upper() # "HELLO" "World".lower() # "world"
title()
/capitalize()
"hello world".title() # "Hello World" "hello world".capitalize() # "Hello world"
swapcase()
"HeLLo".swapcase() # "hEllO"
二、查找與替換
1. 子串查找
find(sub[, start[, end]])
/index(sub[, start[, end]])
s = "Python" s.find("th") # 2(返回索引,未找到返回-1) s.index("th") # 2(未找到拋出 ValueError)
count(sub[, start[, end]])
"ababa".count("aba") # 1(非重疊計數)
2. 替換操作
replace(old, new[, count])
"Hello World".replace("World", "Python") # "Hello Python"
expandtabs(tabsize=8)
"a\tb".expandtabs(4) # "a b"
三、格式化與對齊
1. 格式化字符串
format(*args, **kwargs)
"{} + {} = {}".format(2, 3, 5) # "2 + 3 = 5"
- f-string(Python 3.6+)
name = "Alice" f"Hello, {name}!" # "Hello, Alice!"
2. 對齊與填充
ljust(width[, fillchar])
/rjust(width[, fillchar])
"42".rjust(5, "0") # "00042"
center(width[, fillchar])
"Hi".center(10, "-") # "----Hi----"
zfill(width)
"7".zfill(3) # "007"
四、修剪與檢查
1. 去除空白字符
strip([chars])
/lstrip([chars])
/rstrip([chars])
" Hello ".strip() # "Hello" "##Python##".strip("#") # "Python"
2. 字符串檢查
startswith(prefix[, start[, end]])
/endswith(suffix[, start[, end]])
"file.txt".endswith(".txt") # True
isalnum()
/isalpha()
/isdigit()
/isspace()
"123abc".isalnum() # True(字母或數字) " ".isspace() # True
五、編碼與解碼
1. 編碼轉換
encode(encoding='utf-8', errors='strict')
"中文".encode("utf-8") # b'\xe4\xb8\xad\xe6\x96\x87'
bytes.decode(encoding='utf-8', errors='strict')
b'\xe4\xb8\xad\xe6\x96\x87'.decode("utf-8") # "中文"
六、正則表達式(需 re
模塊)
常用方法:
re.findall(pattern, string)
import re re.findall(r'\d+', "a1b22c") # ['1', '22']
re.sub(pattern, repl, string)
re.sub(r'\s+', '-', "Hello World") # "Hello-World"
注意事項
- 字符串不可變性:所有字符串方法均返回新字符串,原字符串不變。
- 索引規則:Python 字符串索引從
0
開始,支持負數索引(如s[-1]
表示最後一個字符)。 - 切片操作:
s[start:end:step]
(如s[::-1]
反轉字符串)。
總結
Python 的字符串處理功能強大且靈活,結合內置方法和正則表達式可應對多數文本處理需求。建議在實際編碼中根據場景選擇最簡潔高效的方法!