从另一个字符串中删除字符串

时间:2013-08-15 11:23:38

标签: python

我有两个字符串变量 - string_Astring_Bstring_A包含以下内容:

"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"

string_B包含:

"NANA" # "PAA" # "THREE" # "ELI"

我想从string_A中移除string_B中的所有元素。打印string_B后,它应该看起来像"NANA" # "PAA" # "ELI"

更新

x = textA.split(' # ')
y = textB.split(' # ')

for i, j in enumerate(x):
if j in y[i]:
    pass

5 个答案:

答案 0 :(得分:7)

a = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
b = '"NANA" # "PAA" # "THREE" # "ELI"'

a_elements = set(a.split(' # '))
b_elements = [key for key in b.split(' # ') if key not in a_elements]

b = ' # '.join(b_elements)

答案 1 :(得分:2)

直接的解决方案:

a = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
b = '"NANA" # "PAA" # "THREE" # "ELI'

a_elements = [key.strip() for key in a.split('#')]
b_elements = [key.strip() for key in b.split('#')]
filtered_b_elements = [key for key in b_elements if key not in a_elements]
new_b = ' # '.join(filtered_b_elements)

答案 2 :(得分:1)

你去吧:

' # '.join([x for x in string_B.split(' # ') if x not in string_A.split(' # ')])

如果您想获得更好的性能,请先从string_A创建一个列表,然后将其用于“not in”子句。

答案 3 :(得分:1)

对于re粉丝:

import re

e = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
f = '"NANA" # "PAA" # "THREE" # "ELI"'

ea_pattern = re.compile(r'"([a-zA-Z]+)"')
ea = re.findall(ea_pattern,e)
fa = re.findall(ea_pattern,f)

answer = [x for x in fa if x not in ea]
print(answer)

以任何您想要的方式使用此list -

  

['NANA', 'PAA', 'ELI']

答案 4 :(得分:0)

a = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
b = '"NANA" # "PAA" # "THREE" # "ELI"'
x = a.split(' # ')
y = b.split(' # ')

for j in x:
    if j in y:
        #HOW TO REMOVE
        y.remove(j)

xx = ' # '.join(x)
yy = ' # '.join(y)
print xx
print yy

以下输出:

'"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
'"NANA" # "PAA" # "ELI"'