如何在Python中移除字串中的一組字元?


在這篇文章中,我們將學習如何在Python中移除字串中的一組字元。

第一種方法是使用replace()方法。此方法接受兩個引數:要替換的字元和用來替換的字元。此方法接受字串作為輸入,並輸出修改後的字串。

replace字串方法透過將給定字串中的一些字元替換為新的字元來建立一個新的字串。原始字串不受影響且保持不變。

示例

在下面的示例中,我們以字串作為輸入,並使用replace()方法移除不需要的字元列表。

str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

print("Removing the character 't' from the input string")
print(str1.replace('t',''))

輸出

以上示例的輸出如下:

The given string is
Welcome to tutorialspoint
Removing the character 't' from the input string
Welcome o uorialspoin

使用正則表示式

第二種方法涉及使用正則表示式。re.sub技術與正則表示式一起使用。我們使用re.sub()刪除不需要的字元並將它們替換為空格。

示例

在下面的示例中,我們以字串作為輸入,並使用正則表示式移除一組字元。

import re 
str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

print("The updated string is")
print(re.sub("e|t", " ",str1))

輸出

以上示例的輸出如下:

The given string is
Welcome to tutorialspoint
The updated string is
W lcom o u orialspoin

使用join()和生成器

第三種技術是使用生成器的join()函式。我們建立一個不需要的字元列表,然後遍歷字串以檢視字元是否在不需要的字元列表中。如果不是,我們使用join()函式新增該特定字元。

示例

在下面的示例中,我們以字串作為輸入,並使用join()方法移除一組字元。

str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

remove = ['e','t']
str1 = ''.join(x for x in str1 if not x in remove)
print("The updated string is")
print(str1)

輸出

以上示例的輸出如下:

The given string is
Welcome to tutorialspoint
The updated string is
Wlcom o uorialspoin

更新於:2022年12月7日

5K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.