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

5K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.