1

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

1
  • FWIW as an addendum to the answers strip works on a character basis, so .strip('limited') is the same as .strip('deilmt'), as long as it finds marching characters from either end it removes them. Python 3.9.0 added something closer to what you're looking for (str.removesuffix). Commented Nov 4, 2020 at 11:13

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

If i understand this correctly you always want to remove the last word in each sentance?

If that's the case this should work:

lst =['puppies com', 'company abc org', 'company a com', 'python limited']

for i in lst:
    f = i.rsplit(' ', 1)[0]
    print(f)

Returns:

puppies
company abc
company a
python

rsplit is a shorthand for "reverse split", and unlike regular split works from the end of a string. The second parameter is a maximum number of splits to make - e.g. value of 1 will give you two-element list as a result (since there was a single split made, which resulted in two pieces of the input string). As described here

This is also available in the python doc here.

3 Comments

I'd think they only want to remove it if it's one of a number of provided generic words e.g. "puppies com"-> "puppies" but "puppies butts" -> "puppies butts". Basically filtering out stop words.
thank you - not exactly what I was after but still useful for me :)
Glad you found it useful. I didn't catch the predefined words to be removed :)