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

时间:2016-05-22 09:31:05

标签: python python-3.x

我有一组字符串<?php> for ($i = 0; $i <= 9; $i++) { //FROM HERE if ($i >= 5) { $top_position = 493; } else { $top_position = 133; } if ($i >= 5) { $r = 18 + 250 * $i - 250 * 5 - 612.5; } else { $r = 18 + 250 * $i - 612.5; } $runes = getRunes($summoner_currentgame_specified); echo "<style> " . ".runes" . $i . "{" . "position: absolute; left: " . $r . "px;" . "top: " . $top_position . "px; font-size: 16px; color: #fff; font-family: Verdana, Friz Quadrata Thin, sans-serif; font-weight:bold;" . "</style>"; echo "<div id='a' class=runes" . $i . ">Runes</div>"; echo "<style> " . ".runes" . $i . ":hover" . "{" . "position: absolute; background-color: rgba(0, 0, 0, 0.9); width: 225px; height: 300px; margin-left: -21px; margin-top: -273px; text-align: center; border: 1px solid #fff; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 25px;" . "}" . "</style>"; //TO HERE ALL IS WORKING FINE, just for clarity of the code echo "<style>" . ".runestext" . $i . "{ font-family: Verdana; font-style: normal; font-weight: bold; font-size: 16px; color: #fff; text-decoration: none; display: none; }" . "</style>"; echo "<div id='b' class=runestext" . $i . ">RUNESTEXT</div>"; //Here my mistake should be, i just cannot find it: echo "<style>" . ".runes" . $i . ":hover .runestext" . $i . "{" . "display: block;" . "}" . "</style>"; } </php> 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','') 而不是原始版本,但这并没有改变任何内容。

10 个答案:

答案 0 :(得分:98)

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

  

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

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

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

答案 1 :(得分:45)

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'

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

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

答案 2 :(得分:7)

你可以这样做:

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)

答案 3 :(得分:6)

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

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

答案 4 :(得分:3)

针对Python 3.9的更新

python 3.9中,您可以使用str.removesuffix('suffix')删除后缀

docs

如果字符串以后缀字符串结尾并且后缀不为空,则返回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"))

或使用集合理解:

set2 = {s.removesuffix(".good").removesuffix(".bad") for s in set1}
   
print(set2)


Output:
{'Orange', 'Pear', 'Apple', 'Banana', 'Potato'}

答案 5 :(得分:2)

我做了测试(但不是你的例子)并且数据没有按顺序或完整地返回

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}

我证明这有效:

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']

>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
...     newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']

答案 6 :(得分:1)

如果列表

我正在为列表做一些事情,这是一组字符串,你想删除所有具有某个子字符串的行,你可以这样做

import re
def RemoveInList(sub,LinSplitUnOr):
    indices = [i for i, x in enumerate(LinSplitUnOr) if re.search(sub, x)]
    A = [i for j, i in enumerate(LinSplitUnOr) if j not in indices]
    return A

其中sub是您不希望在行列表LinSplitUnOr

中出现的模式

例如

A=['Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad']
sub = 'good'
A=RemoveInList(sub,A)

然后A将是

enter image description here

答案 7 :(得分:1)

当要删除多个子字符串时,一个简单有效的选择是将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']

答案 8 :(得分:1)

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

 

print : Amin Is A  Programmer

答案 9 :(得分:0)

如果您从列表中删除某项, 您可以使用这种方式: (方法子区分大小写)

new_list = []
old_list= ["ABCDEFG","HKLMNOP","QRSTUV"]

for data in old_list:
     new_list.append(re.sub("AB|M|TV", " ", data))

print(new_list) // output : [' CDEFG', 'HKL NOP', 'QRSTUV']