I have a bunch of strings, some of them have \' rec\'
. I want to remove that only if those are the last 4 characters.
So in other words I have
You could use a regular expression as well:
from re import sub
str = r"this is some string rec"
regex = r"(.*)\srec$"
print sub(regex, r"\1", str)
Here is a one-liner version of Jack Kelly's answer along with its sibling:
def rchop(s, sub):
return s[:-len(sub)] if s.endswith(sub) else s
def lchop(s, sub):
return s[len(sub):] if s.startswith(sub) else s
def remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content
use:
somestring.rsplit(' rec')[0]
Using more_itertools, we can rstrip
strings that pass a predicate.
Installation
> pip install more_itertools
Code
import more_itertools as mit
iterable = "this is some string rec".split()
" ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "}))
# 'this is some string'
" ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "}))
# 'this is some string'
Here we pass all trailing items we wish to strip from the end.
See also the more_itertools docs for details.
As kind of one liner generator joined:
test = """somestring='this is some string rec'
this is some string in the end word rec
This has not the word."""
match = 'rec'
print('\n'.join((line[:-len(match)] if line.endswith(match) else line)
for line in test.splitlines()))
""" Output:
somestring='this is some string rec'
this is some string in the end word
This has not the word.
"""