如何在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

更新於:2022年10月19日

2K+ 次檢視

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.