Home > Software engineering >  Replace substring inside a list
Replace substring inside a list

Time:07-26

I have a list of strings with a few unclean entries and I want to replace the unclean entries with clean entries

list = ['created_DATE', 'column1(case', 'timestamp', 'location(case']

I want to get a list that is like this

cleanList = ['created_DATE', 'column1', 'timestamp', 'location']

I tired the following:

str_match = [s for s in list if "(case" in s]     *#find the intersecting elements*
print (str_match)

new=[]
for k in str_match:
   a=k.replace("(case" , "")
   new.append(a)           *#make an list of the words without the substring*
print(new)

I am not sure how do I now replace the entries from the new list into the original list. Can someone please help. Thank you

CodePudding user response:

If you want to remove all occurrences of "case(" from your list's elements, then you could write it like this:

list = ['created_DATE', 'column1(case', 'timestamp', 'location(case']
clean = []

for n in list:
    clean.append(n.replace("(case", ""))
    
print(clean)

CodePudding user response:

You can either create a new list clean as told by @alani:

import re

myList = ['created_DATE', 'column1(case', 'timestamp', 'location(case']

clean = [re.sub("\(.*", "", s) for s in myList]

print(clean)

or iterate over elements of myList and update in place

for i in range(len(myList)):
  if "(case" in myList[i]:
    myList[i] = myList[i].replace("(case" , "")
print(myList)
  • Related