首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Python 字串操作完全指南:串接、切片、取代與格式化

     編輯:Java 相關知識

Python 字串處理核心技巧總整理

字串是 Python 最常用的資料型別,掌握高效操作方式能顯著提升程式效能與可讀性。

一、字串串接:三種方式效能大比拚

❌ 低效方式:+ 運算子迴圈累加

a = ['a','b','c','d']
content = ''
for i in a:
    content = content + i  # 每次建立新字串物件,記憶體分配/釋放頻繁
print(content)  # 'abcd'

缺點:字串不可變,每次 + 都產生新物件,O(n²) 時間複雜度,大量資料極慢。

✅ 推薦方式 1:str.join() - 最高效

a = ['a','b','c','d']
content = ''.join(a)  # 一次性分配記憶體並複製
print(content)  # 'abcd'

優點:C 層實作,一次計算總長度並分配,O(n) 複雜度,標準庫最佳實踐。

✅ 推薦方式 2:格式化佔位符 % 或 format()

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' (反轉)

三、字串取代:replace() 與正則 re.sub()

1. 簡單取代:str.replace(old, new[, count])

'hello word'.replace('word', 'python')  # 'hello python'
'aaa'.replace('a', 'b', 2)  # 'bba' (僅前 2 次)

2. 正則取代:re.sub(pattern, repl, string[, count])

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!'

四、進階格式化:f-string (Python 3.6+)

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' 格式化規格

效能基準測試參考 (10萬次迴圈串接 10 字元)

方法相對耗時建議場景
+ 迴圈累加100x (基準)極少量、一次性
% 格式化~1.2x固定模板
format()~1.3x複雜模板
join()1x (最快)列表/序列串接首選
f-string~1.1x變數內嵌、可讀性最佳

最佳實踐總結

  1. 列表/序列串接 → ''.join(list)
  2. 變數內嵌輸出 → f'...{var}...' (Py3.6+)
  3. 固定模板多次使用 → template = '{} {}'; template.format(a, b)
  4. 複雜模式取代 → re.sub()
  5. 大量字串建構 → io.StringIO 或列表 append 最後 join
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved