我有两个字符串变量 - string_A
和string_B
。 string_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
答案 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"'