Python replace 取代字串用法與範例

本篇 ShengYu 介紹 Python replace 取代字串的用法與範例,str.replace 就是將字串中的舊字串取代成新字串,str.replace 是不會改變原本字串內容,而是會另外回傳新的結果字串。

以下 Python replace 取代字串用法與範例將分為這幾部份,

  • Python replace 語法參數
  • Python replace 基本使用範例
  • Python replace 單次與取代與多次取代

那我們開始吧!

Python replace 語法參數

Python str.replace 語法參數如下,

1
str.replace(old, new[, max])

參數說明
old:將被取代的子字串
new:用於取代 old 子字串的新字串
max:可選參數,取代字串不超過 max 次

回傳值
回傳取代後新的結果字串。

Python replace 基本使用範例

Python 的 str replace 用處在於把字串中的原本字串(old)取代成新的字串(new),
str.replace(old, new) 使用語法為把第一個參數(old)取代為第二個參數(new),
以下範例是在 Python 3 環境下測試過,也可以在 Python 2.7 環境下執行,程式碼如下:

python3-replace.py
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

str1 = 'abc,de,f'
print('str: ' + str1)
print('str: ' + str1.replace('de', '123'))
str2 = str1.replace('b', '45')
print('str: ' + str2)

輸出結果如下:

1
2
3
str: abc,de,f
str: abc,123,f
str: a45c,de,f

Python replace 單次與取代與多次取代

如果要限定次數取代的話,可以在 replace(old, new, max) 的第三個參數指定次數,不帶入第三個參數的話,預設是無限次。
程式碼如下:

python3-replace2.py
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

str1 = 'abcdef,abcde,abcde'
print('str: ' + str1)
str2 = str1.replace('cd', '34')
print('str: ' + str2)
str3 = str2.replace('ab', '12', 2)
print('str: ' + str3)

輸出結果如下:

1
2
3
str: abcdef,abcde,abcde
str: ab34ef,ab34e,ab34e
str: 1234ef,1234e,ab34e

下一篇介紹 strip 去除空白與去除特殊字元

以上就是 Python replace 取代字串用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python str 字串用法與範例
Python 新手入門教學懶人包
Python 字串分割 split
Python 連接字串 join
Python 去除空白與去除特殊字元 strip
Python 取出檔案名稱 basename
Python 取出目錄的路徑 dirname