字串是 Python 最核心的資料類型之一。Python 3 全面採用 Unicode (UTF-8 內部表示),字串為**不可變序列**。本文系統整理字串建立方式、編碼處理、格式化語法、核心方法、記憶體特性與效能優化技巧。
# 基本字面值
s1 = 'single quote'
s2 = "double quote"
s3 = '''triple single'''
s4 = """triple double""" # 多行字串、文件字串
# 原始字串 (關閉轉義)
r'C:\Users\name' # Windows 路徑
r'\d+\.\d+' # 正則表達式
# Unicode 前綴 (Python 3 所有字串皆 Unicode,u 前綴相容但無實際作用)
u'中文' # 等同 '中文'
# 位元組串 (bytes)
b'bytes'
b'hello'.decode('utf-8') # bytes -> str
'hello'.encode('utf-8') # str -> bytes
s = 'hello'
# s[0] = 'H' # TypeError: 'str' object does not support item assignment
# 修改必須建立新字串
s2 = 'H' + s[1:] # 連接
s3 = s.replace('h', 'H') # 替換
s4 = s.upper() # 方法返回新字串
**效能啟示**:大量拼接用列表 `join` 或 `io.StringIO`,避免 `+=` 產生大量中間物件。
# 編碼: str -> bytes
text = '中文'
utf8_bytes = text.encode('utf-8') # b'\xe4\xb8\xad\xe6\x96\x87'
gbk_bytes = text.encode('gbk') # b'\xd6\xd0\xce\xc4'
# 解碼: bytes -> str
utf8_bytes.decode('utf-8') # '中文'
gbk_bytes.decode('gbk') # '中文'
# 錯誤處理
b'\x80\x81'.decode('utf-8', errors='strict') # UnicodeDecodeError (預設)
b'\x80\x81'.decode('utf-8', errors='ignore') # 忽略錯誤位元組
b'\x80\x81'.decode('utf-8', errors='replace') # 替換為
b'\x80\x81'.decode('utf-8', errors='backslashreplace') # \x80\x81
'%s is %d' % ('Alice', 25) # 位置參數
'%(name)s is %(age)d' % {'name': 'Alice', 'age': 25} # 字典參數
'%05d' % 42 # '00042' (補零)
'%.2f' % 3.14159 # '3.14' (小數位)
'{} is {}'.format('Alice', 25)
'{name} is {age}'.format(name='Alice', age=25)
'{0} {1} {0}'.format('a', 'b') # 位置索引重用
'{:05d}'.format(42) # '00042'
'{:.2%}'.format(0.1234) # '12.34%' (百分比)
'{0[0]} {0[1]}'.format(['a', 'b']) # 索引存取
'{obj.name}'.format(obj=user) # 屬性存取
name = 'Alice'
age = 25
f'{name} is {age}' # 變數直接嵌入
f'{name.upper()} is {age + 1}' # 任意運算式
f'{age:05d}' # 格式規範
f'{3.14159:.2f}' # '3.14'
f'{0.1234:.2%}' # '12.34%'
f'{"left":<10}{"right":>10}{"center":^10}' # 對齊
f'{1/3:.2%}' # '33.33%'
**f-string 優勢**:語法簡潔、執行速度最快 (編譯時優化)、支援完整運算式、除錯支援 (`f'{var=}'` → `'var=value'`)。
| 類別 | 方法 | 說明 |
|---|---|---|
| 查找/判斷 | find/sub/index | 子串位置 (find 找不到 -1, index 拋異常) |
rfind/rindex | 反向查找 | |
startswith/endswith | 前綴/後綴判斷,支援元組多選項 | |
in / not in | 子串包含判斷 (最常用) | |
isalpha/isdigit/isalnum | 字元類型判斷 | |
islower/isupper/istitle | 大小寫/標題格式判斷 | |
isspace | 全空白判斷 | |
isprintable | 可列印字元判斷 | |
| 修改/轉換 | upper/lower/swapcase/title/capitalize | 大小寫轉換 |
strip/lstrip/rstrip([chars]) | 移除首尾字元 (預設空白) | |
replace(old, new[, count]) | 替換 (count 限制次數) | |
split(sep[, maxsplit]) | 分割列表 | |
splitlines([keepends]) | 按行分割 | |
join(iterable) | 連接 (分隔符為調用者) | |
partition/rpartition(sep) | 分割為 (前, 分隔符, 後) 三元組 | |
expandtabs(tabsize=8) | Tab 展開為空格 | |
| 格式化/編碼 | format/__format__ | 進階格式化協定 |
encode/decode | 編碼轉換 | |
zfill(width) | 左側補零 | |
center/ljust/rjust(width[, fillchar]) | 置中/左/右對齊填充 | |
maketrans/translate | 字元映射轉換 (高效批量替換) | |
__mod__ | % 運算子實現 |
# 反轉字串
s[::-1]
# 移除前綴/後綴 (Python 3.9+)
s.removeprefix('pre_')
s.removesuffix('_suf')
# 多行字串去除縮進
import textwrap
textwrap.dedent('''\
line 1
line 2
''')
# 截斷並添加省略號
def truncate(s, max_len=100, ellipsis='...'):
return s if len(s) <= max_len else s[:max_len-len(ellipsis)] + ellipsis
# 變數名合法化 (檔案名、識別符)
import re
def sanitize(s):
return re.sub(r'[^\w\-_.]', '_', s)
# 安全獲取字典值並格式化
'{name} is {age}'.format(**{'name': 'Alice', 'age': 25})