evil007
evil007

Reputation: 13

I want to replace multiple strings with blanks in a single replace function

I want to replace string with blank. For below script it works but when I have multiple string with different strings to replacce it with blanks I am getting stucked.

for example: ( I am getting list of string using xpath etxtract, for that suppose 8 strings are same, 3 strings are same, 2 strings are same,......)

links = [ 'ABCDEFGH google', 'ABCDEFGH google', 'Samsung mobile',  
'ABCDEFGH serachgoogle google', 'ABCDEFGH google',  'XYZacbxf 
12153131' , 'Samsung mobile', 'Apple smartphone x10',.............]

m = []
for link in links:
    temp = link.replace("ABCD", '')
    m.append(temp)

(In above first i am replacing 'ABCD' with blank, and seond I want to replace 'ABCD' with blank, third i want to replace "mobile" with blank, upto 20+ difference strings with blanks in a single replce function) (I don't know is it possible or not!, Someone have idea about this please help.) (Thanks in advance!)

Have tried=>

m = []
for link in links:
    temp = link.replace("ABCD", '' or "mobile", '' or "google", 
'' or ...........upto available replacing string) 
    m.append(temp)

Upvotes: 0

Views: 804

Answers (3)

Austin
Austin

Reputation: 26039

Without using an additional list, you can use regex to replace unnecessary strings from each element of list.

The regex looks like:

re.sub(r'ABCD|mobile', '', x)

Code:

import re

links = [ 'ABCDEFGH google', 'ABCDEFGH google', 'Samsung mobile',  'ABCDEFGH serachgoogle google', 'ABCDEFGH google',  'XYZacbxf 12153131' , 'Samsung mobile', 'Apple smartphone x10']

res = []
for x in links:
    res.append(re.sub(r'ABCD|mobile', '', x))

print(res)
# ['EFGH google', 'EFGH google', 'Samsung ', 'EFGH serachgoogle google', 'EFGH google', 'XYZacbxf 12153131', 'Samsung ', 'Apple smartphone x10']

Upvotes: 1

gmds
gmds

Reputation: 19885

You should use a regex which will match all the terms you want to replace:

import re

links = ['ABCDEFGH google', 'ABCDEFGH google', 'Samsung mobile',  
'ABCDEFGH serachgoogle google', 'ABCDEFGH google',  'XYZacbxf',
'12153131' , 'Samsung mobile', 'Apple smartphone x10']

to_replace = ['ABCD', 'mobile', 'google']
regex = re.compile('|'.join(to_replace))

new_links = [re.sub(regex, '', link) for link in links]
print(new_links)

Output:

['EFGH ', 'EFGH ', 'Samsung ', 'EFGH serach ', 'EFGH ', 'XYZacbxf', '12153131', 'Samsung ', 'Apple smartphone x10']

Upvotes: 2

Matt
Matt

Reputation: 1198

You could do it this way by also iterating over the strings to replace:

to_replace_terms = ['ABCD', 'mobile', 'google']
m = []
for link in links:
    for to_replace_term in to_replace_terms:
        link = link.replace(to_replace_term, '')
    m.append(link)

Note that you need to assign the replacement back to link since multiple replacements might happen.

Upvotes: 0

Related Questions