如何从Python中的一组字符串中删除特定的子串?

con*_*eak 117 python python-3.x

我有一组字符串set1,并且所有字符串set1都有两个特定的子字符串,我不需要并且想要删除它们.
示例输入: set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
基本上我希望从所有字符串中删除.good.bad子串.
我尝试了什么:

for x in set1:
    x.replace('.good','')
    x.replace('.bad','')
Run Code Online (Sandbox Code Playgroud)

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

Reu*_*ani 132

字符串是不可变的.string.replace创建一个字符串.这在文档中说明:

返回字符串s 的副本,其中所有出现的substring old都替换为new....

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

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}
Run Code Online (Sandbox Code Playgroud)

  • 注意:它也适用于列表,只需使用“[...]”而不是“{...}” (3认同)
  • 通过复制 @DineshKumar 的答案来编辑此问题以使用 Python 3.9+ 的 str.removesuffix() 进行更新有什么意义?让人们相信该答案的作者是更公平的。 (2认同)

Ale*_*all 49

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'
Run Code Online (Sandbox Code Playgroud)

.replace更改字符串,它返回替换字符串的副本.您无法直接更改字符串,因为字符串是不可变的.

您需要从中获取返回值x.replace并将它们放入新集合中.


Din*_*mar 9

Python 3.9 + 中,您可以使用str.removesuffix('mysuffix'). 从文档

如果字符串以后缀字符串结尾并且该后缀不为空,则返回string[:-len(suffix)]. 否则,返回原始字符串的副本

因此,您可以创建一个新的空集并添加每个不带后缀的元素:

set1  = {'Apple.good', 'Orange.good', 'Pear.bad', 'Pear.good', 'Banana.bad', 'Potato.bad'}

set2 = set()
for s in set1:
   set2.add(s.removesuffix(".good").removesuffix(".bad"))
Run Code Online (Sandbox Code Playgroud)

或者使用集合推导创建新集合:

set2 = {s.removesuffix(".good").removesuffix(".bad") for s in set1}
   
print(set2)
Run Code Online (Sandbox Code Playgroud)

输出:

{'Orange', 'Pear', 'Apple', 'Banana', 'Potato'}
Run Code Online (Sandbox Code Playgroud)


小智 7

您所需要的只是一点黑魔法!

>>> a = ["cherry.bad","pear.good", "apple.good"]
>>> a = list(map(lambda x: x.replace('.good','').replace('.bad',''),a))
>>> a
['cherry', 'pear', 'apple']
Run Code Online (Sandbox Code Playgroud)


Ami*_*deh 7

# practices 2
str = "Amin Is A Good Programmer"
new_set = str.replace('Good', '')
print(new_set)

 

print : Amin Is A  Programmer
Run Code Online (Sandbox Code Playgroud)


cs9*_*s95 6

当要删除多个子字符串时,一个简单而有效的选择是使用re.sub编译模式,该模式涉及使用正则表达式 OR ( |) 管道连接所有要删除的子字符串。

import re

to_remove = ['.good', '.bad']
strings = ['Apple.good','Orange.good','Pear.bad']

p = re.compile('|'.join(map(re.escape, to_remove))) # escape to handle metachars
[p.sub('', s) for s in strings]
# ['Apple', 'Orange', 'Pear']
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以这样做:

import re
import string
set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}

for x in set1:
    x.replace('.good',' ')
    x.replace('.bad',' ')
    x = re.sub('\.good$', '', x)
    x = re.sub('\.bad$', '', x)
    print(x)
Run Code Online (Sandbox Code Playgroud)

  • 第x.replace('。good','')和x.replace('。bad','')`行对最终结果没有任何作用。没有它们,打印输出将相同。 (2认同)

归档时间:

查看次数:

251691 次

最近记录:

6 年,4 月 前