如何在Python中將字串的所有出現替換為另一個字串?
字串是一組字元,可用於表示單個單詞或整個短語。在 Python 中,字串不需要顯式宣告,可以有或沒有說明符進行定義,因此使用起來很容易。
Python 具有各種內建函式和方法來操作和訪問字串。因為 Python 中的一切都是物件,所以字串是 String 類的物件,它有幾個方法。
在本文中,我們將重點介紹如何在 Python 中將字串的所有出現替換為另一個字串。
使用 replace() 方法
字串類的 replace() 方法接受字串值作為輸入,並返回修改後的字串作為輸出。它有兩個必填引數和一個可選引數。以下是此方法的語法。
string.replace(oldvalue, newvalue, count)
其中,
舊值 - 你想要替換的子字串。
新值 - 你想要替換的子字串。
計數 - 這是一個可選引數;它用於指定要將多少箇舊值替換為新值。
示例 1
在下面的程式中,我們取一個輸入字串,並使用 replace 方法將字母“t”替換為“d”。
str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d") print(str1.replace("t","d"))
輸出
上述程式的輸出為:
The given string is Welcome to tutorialspoint After replacing t with d Welcome do dudorialspoind
示例 2
在下面的程式中,我們取相同的輸入字串,並使用 replace() 方法將字母“t”替換為“d”,但在本例中,我們將計數引數設定為 2。因此,只轉換了 2 個 t 的出現。
str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d for 2 times") print(str1.replace("t","d",2))
輸出
上述程式的輸出為:
The given string is Welcome to tutorialspoint After replacing t with d for 2 times Welcome do dutorialspoint
使用正則表示式
我們還可以使用 Python 正則表示式將字串的所有出現替換為另一個字串。Python re 的 sub() 方法將給定字串中的現有字母替換為新字母。以下是此方法的語法:
re.sub(old, new, string);
舊值 - 你想要替換的子字串。
新值 - 你想要替換的新子字串。
字串 - 源字串。
示例
在下面的示例中,我們使用 re 庫的 sub 方法將字母“t”替換為“d”。
import re str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d ") print(re.sub("t","d",str1))
輸出
上述程式的輸出為:
The given string is Welcome to tutorialspoint After replacing t with d Welcome do dudorialspoind
遍歷每個字元
另一種方法是蠻力方法,你遍歷特定字串的每個字元,並將其與你想要替換的字元進行比較,如果匹配則替換該字元,否則繼續前進。
示例
在下面的示例中,我們正在迭代字串並匹配每個字元並替換它們。
str1= "Welcome to tutorialspoint" new_str = '' for i in str1: if(i == 't'): new_str += 'd' else: new_str += i print("The original string is") print(str1) print("The string after replacing t with d ") print(new_str)
輸出
上述程式的輸出為:
The original string is Welcome to tutorialspoint The string after replacing t with d Welcome do dudorialspoind
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP