Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a string from another string [closed]

Tags:

python

I have two string variables - string_A and string_B. string_A contains the following:

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

and string_B contains:

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

I want to remove all the elements that are in string_A from string_B. After I print string_B it should look like "NANA" # "PAA" # "ELI"

Update:

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

for i, j in enumerate(x):
if j in y[i]:
    pass
like image 476
Sharon Watinsan Avatar asked Dec 20 '22 01:12

Sharon Watinsan


2 Answers

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)
like image 146
John La Rooy Avatar answered Jan 08 '23 11:01

John La Rooy


A straight-forward solution:

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)
like image 27
Magnus Grindal Bakken Avatar answered Jan 08 '23 11:01

Magnus Grindal Bakken