I have a list of strings:
lst =['puppies com', 'company abc org', 'company a com', 'python limited']
If at the end of the string there is the word
limited, com or org I would like to remove it. How can I go about doing this?
I have tried;
for item in lst: j= item.strip('limited') j= item.strip('org')
I’ve also tried the replace function with no avail.
Thanks
Advertisement
Answer
You can use this example to remove selected last words from the list of string:
lst =['dont strip this', 'puppies com', 'company abc org', 'company a com', 'python limited'] to_strip = {'limited', 'com', 'org'} out = [] for item in lst: tmp = item.rsplit(maxsplit=1) if tmp[-1] in to_strip: out.append(tmp[0]) else: out.append(item) print(out)
Prints:
['dont strip this', 'puppies', 'company abc', 'company a', 'python']