Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove substring only at the end of string

Tags:

python

string

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

somestring = 'this is some string rec' 

and I want it to become

somestring = 'this is some string' 

What is the Python way to approach this?

like image 814
Alex Gordon Avatar asked Sep 07 '10 23:09

Alex Gordon


People also ask

How do you remove the last part of a string in Python?

Using rstrip() to remove the last character The rstrip() is a built-in Python function that returns a String copy with trailing characters removed. For example, we can use the rstrip() function with negative indexing to remove the final character of the string.

How do I remove a specific part of a string?

To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.

How do I remove a suffix in Python?

There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .


1 Answers

def rchop(s, suffix):     if suffix and s.endswith(suffix):         return s[:-len(suffix)]     return s  somestring = 'this is some string rec' rchop(somestring, ' rec')  # returns 'this is some string' 
like image 72
Jack Kelly Avatar answered Sep 21 '22 17:09

Jack Kelly