字串串接是日常開發高頻操作,Python join() 方法以高效能、記憶體友善、語法清晰著稱,是官方推薦的標準串接方式。本文詳細說明語法、運作原理、效能優勢、常見陷阱與進階應用模式。
separator.join(iterable)
'')。#!/usr/bin/python3
# 範例 1:基本用法
seq = ("a", "b", "c")
print("-".join(seq)) # a-b-c
print("".join(seq)) # abc(無分隔)
print(", ".join(seq)) # a, b, c
# 範例 2:列表串接
words = ["Python", "是", "很棒的", "語言"]
print(" ".join(words)) # Python 是 很棒的 語言
# 範例 3:路徑組合
path_parts = ["home", "user", "documents", "file.txt"]
print("/".join(path_parts)) # home/user/documents/file.txt
# 範例 4:CSV 格式產生
row = ["張三", "25", "台北市", "工程師"]
print(",".join(row)) # 張三,25,台北市,工程師
# 範例 5:產生器表達式(記憶體高效)
numbers = (str(i) for i in range(1000000))
result = ",".join(numbers) # 不建立中間列表,直接串接
| 方式 | 時間複雜度 | 記憶體分配 | 適用場景 |
|---|---|---|---|
| join() | O(N) | 單次分配 | 大量字串串接、效能關鍵 |
| + / += | O(N²) | 每次新建字串 | 少量(<5)簡單串接 |
| % 格式化 | O(N) | 多次分配 | 固定模板、少量變數 |
| f-string | O(N) | 單次分配 | Python 3.6+、可讀性佳 |
| StringIO | O(N) | 緩衝區 | 極大量、串流式建構 |
import timeit
# 串接 10000 個字串
setup = "parts = ['a'] * 10000"
t_join = timeit.timeit("''.join(parts)", setup=setup, number=100)
t_plus = timeit.timeit("s=''; [s:=s+p for p in parts]", setup=setup, number=100)
print(f"join(): {t_join:.4f}s") # ~0.02s
print(f"+=: {t_plus:.4f}s") # ~1.5s(慢 75 倍!)
TypeError。
# 錯誤
",".join([1, 2, 3]) # TypeError
# 正確:先轉字串
",".join(str(x) for x in [1, 2, 3]) # "1,2,3"
",".join(map(str, [1, 2, 3])) # 同上
# 錯誤預期
"-".join("abc") # "a-b-c",非 "abc"
# 若只想要原字串
"-".join(["abc"]) # "abc"
TypeError,必須是字串。parts = ["固定前綴"]
if condition:
parts.append("動態內容")
parts.append("固定後綴")
result = "".join(parts)
lines = [
"第一行內容",
"第二行內容",
"第三行內容"
]
text = "\n".join(lines)
columns = ["id", "name", "email", "created_at"]
placeholders = ", ".join(["%s"] * len(columns))
sql = f"INSERT INTO users ({', '.join(columns)}) VALUES ({placeholders})"
# INSERT INTO users (id, name, email, created_at) VALUES (%s, %s, %s, %s)
csv_line = "張三,25,台北市,工程師"
fields = csv_line.split(",") # ['張三', '25', '台北市', '工程師']
rejoined = ",".join(fields) # 還原
join() 是 Python 字串串接的黃金標準:O(N) 效能、單次記憶體分配、語義清晰。養成「收集字串列表 → 最後 join()」習慣,能寫出高效能、可維護的程式碼。記住:元素必須為字串,非字串先用 map(str, ...) 或產生器表達式轉換。