首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从python列表中删除子字符串

从Python列表中删除子字符串可以使用列表推导式和字符串的replace()方法。

方法一:使用列表推导式 列表推导式可以用来创建一个新的列表,其中不包含指定的子字符串。

代码语言:txt
复制
my_list = ['apple', 'banana', 'orange', 'grape']
substring = 'an'

new_list = [x for x in my_list if substring not in x]

这里的x for x in my_list if substring not in x表示遍历my_list中的每个元素x,如果substring不在x中,则将x添加到新列表new_list中。

方法二:使用replace()方法 replace()方法可以用来替换字符串中的指定子字符串为空字符串,从而实现删除子字符串的效果。

代码语言:txt
复制
my_list = ['apple', 'banana', 'orange', 'grape']
substring = 'an'

new_list = [x.replace(substring, '') for x in my_list]

这里的x.replace(substring, '')表示将x中的substring替换为空字符串。

以上两种方法都可以实现从Python列表中删除子字符串的功能,具体使用哪种方法取决于你的需求和偏好。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

15秒

Python中如何将字符串转化为整形

领券