如何从 Python 中的一组字符串中删除特定的子字符串? [英] How to remove specific substrings from a set of strings in Python?

查看:98
本文介绍了如何从 Python 中的一组字符串中删除特定的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组字符串 set1set1 中的所有字符串都有两个特定的子字符串,我不需要这些子字符串,也不想删除它们.
样本输入:set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
所以基本上我希望从所有字符串中删除 .good.bad 子字符串.
我的尝试:

I have a set of strings set1, and all the strings in set1 have a two specific substrings which I don't need and want to remove.
Sample Input: set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
So basically I want the .good and .bad substrings removed from all the strings.
What I tried:

for x in set1:
    x.replace('.good','')
    x.replace('.bad','')

但这似乎根本不起作用.输出绝对没有变化,它与输入相同.我尝试使用 for x in list(set1) 而不是原始的,但这不会改变任何东西.

But this doesn't seem to work at all. There is absolutely no change in the output and it is the same as the input. I tried using for x in list(set1) instead of the original one but that doesn't change anything.

推荐答案

字符串是不可变的.str.replace 创建一个 <强>新字符串.文档中对此进行了说明:

Strings are immutable. str.replace creates a new string. This is stated in the documentation:

str.replace(old, new[, count])

返回字符串的副本,其中所有出现的子字符串 old 替换为 new.[...]

Return a copy of the string with all occurrences of substring old replaced by new. [...]

这意味着您必须重新分配集合或重新填充它(使用 集合理解):

This means you have to re-allocate the set or re-populate it (re-allocating is easier with a set comprehension):

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}

这篇关于如何从 Python 中的一组字符串中删除特定的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆