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?
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.
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.
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() .
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With