字串是 Python 最常用的資料型別,掌握高效操作方式能顯著提升程式效能與可讀性。
a = ['a','b','c','d']
content = ''
for i in a:
content = content + i # 每次建立新字串物件,記憶體分配/釋放頻繁
print(content) # 'abcd'
缺點:字串不可變,每次 + 都產生新物件,O(n²) 時間複雜度,大量資料極慢。
a = ['a','b','c','d']
content = ''.join(a) # 一次性分配記憶體並複製
print(content) # 'abcd'
優點:C 層實作,一次計算總長度並分配,O(n) 複雜度,標準庫最佳實踐。
a = ['a','b','c','d']
content = '%s%s%s%s' % tuple(a)
# 或
content = '{}{}{}{}'.format(*a)
print(content) # 'abcd'
適用於固定欄位模板,可讀性佳。
Python 字串為有序序列,支援正向 (0~len-1) 與反向 (-1~-len) 索引。
s = 'ilovepython'
# 單字元
s[0] # 'i'
s[-1] # 'n'
# 切片 [start:end:step] - 含頭不含尾
s[1:5] # 'love' (索引 1 到 4)
s[:6] # 'ilovep' (從頭到 5)
s[2:] # 'ovepython' (從 2 到尾)
s[::2] # 'ioephn' (間隔 1 取值)
s[::-1] # 'nohtypevoli' (反轉)
'hello word'.replace('word', 'python') # 'hello python'
'aaa'.replace('a', 'b', 2) # 'bba' (僅前 2 次)
import re
text = 'hello word, word!'
re.sub(r'word', 'python', text) # 'hello python, python!'
re.sub(r'word', 'python', text, count=1) # 'hello python, word!'
name = 'Alice'
age = 25
f'Hello {name}, you are {age} years old.' # 'Hello Alice, you are 25 years old.'
f'Next year: {age + 1}' # 運算式內嵌
f'{3.14159:.2f}' # '3.14' 格式化規格
| 方法 | 相對耗時 | 建議場景 |
|---|---|---|
+ 迴圈累加 | 100x (基準) | 極少量、一次性 |
% 格式化 | ~1.2x | 固定模板 |
format() | ~1.3x | 複雜模板 |
join() | 1x (最快) | 列表/序列串接首選 |
f-string | ~1.1x | 變數內嵌、可讀性最佳 |
''.join(list)f'...{var}...' (Py3.6+)template = '{} {}'; template.format(a, b)re.sub()io.StringIO 或列表 append 最後 join