Python 如何从字符串中删除字符列表

Python 如何从字符串中删除字符列表

在本文中,我们将找出如何在Python中从字符串中删除字符列表。

第一种方法是使用 replace() 方法。这个方法接受2个参数,我们想要替换的字符和我们替换的字符。这个方法以字符串作为输入,我们将得到修改后的字符串作为输出。

替换字符串方法通过用新字符替换给定字符串中的某些字符来创建新字符串。初始字符串不受影响,也不会改变。

示例

在下面的示例中,我们以一个字符串作为输入,使用 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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程