I have a list of strings:
JavaScript
x
2
1
lst =['puppies com', 'company abc org', 'company a com', 'python limited']
2
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;
JavaScript
1
4
1
for item in lst:
2
j= item.strip('limited')
3
j= item.strip('org')
4
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:
JavaScript
1
13
13
1
lst =['dont strip this', 'puppies com', 'company abc org', 'company a com', 'python limited']
2
to_strip = {'limited', 'com', 'org'}
3
4
out = []
5
for item in lst:
6
tmp = item.rsplit(maxsplit=1)
7
if tmp[-1] in to_strip:
8
out.append(tmp[0])
9
else:
10
out.append(item)
11
12
print(out)
13
Prints:
JavaScript
1
2
1
['dont strip this', 'puppies', 'company abc', 'company a', 'python']
2