python: remove substring only at the end of string

python remove substring from string
python remove substring from beginning of string
python remove character from string by index
python remove last character from string
python strip
python substring
python remove substring regex
python string replace

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 another words

somestring='this is some string rec'

i want it to be:

somestring='this is some string'

what is the python way to approach this?

def rchop(thestring, ending):
  if thestring.endswith(ending):
    return thestring[:-len(ending)]
  return thestring

somestring = rchop(somestring, ' rec')

How do I remove a substring from the end of a string in Python , strip strips the characters given from both ends of the string, in your case it strips ".", "c", "o" and "m". – It will also remove those characters from the front of the string. Yeah. Plus, this removes the characters in any order: "site.ocm" > "site". – This does not always work. It will split at the string at all occurrences of ` rec` and return the first fragment. The prefix l and r only make a difference, if the separator string can overlap or a maximum number of splits is specified. – jan-glx Oct 16 '18 at 18:27.

Since you have to get len(trailing) anyway (where trailing is the string you want to remove IF it's trailing), I'd recommend avoiding the slight duplication of work that .endswith would cause in this case. Of course, the proof of the code is in the timing, so, let's do some measurement (naming the functions after the respondents proposing them):

import re

astring = 'this is some string rec'
trailing = ' rec'

def andrew(astring=astring, trailing=trailing):
    regex = r'(.*)%s$' % re.escape(trailing)
    return re.sub(regex, r'\1', astring)

def jack0(astring=astring, trailing=trailing):
    if astring.endswith(trailing):
        return astring[:-len(trailing)]
    return astring

def jack1(astring=astring, trailing=trailing):
    regex = r'%s$' % re.escape(trailing)
    return re.sub(regex, '', astring)

def alex(astring=astring, trailing=trailing):
    thelen = len(trailing)
    if astring[-thelen:] == trailing:
        return astring[:-thelen]
    return astring

Say we've named this python file a.py and it's in the current directory; now, ...:

$ python2.6 -mtimeit -s'import a' 'a.andrew()'
100000 loops, best of 3: 19 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.jack0()'
1000000 loops, best of 3: 0.564 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.jack1()'
100000 loops, best of 3: 9.83 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.alex()'
1000000 loops, best of 3: 0.479 usec per loop

As you see, the RE-based solutions are "hopelessly outclassed" (as often happens when one "overkills" a problem -- possibly one of the reasons REs have such a bad rep in the Python community!-), though the suggestion in @Jack's comment is way better than @Andrew's original. The string-based solutions, as expected, shing, with my endswith-avoiding one having a miniscule advantage over @Jack's (being just 15% faster). So, both pure-string ideas are good (as well as both being concise and clear) -- I prefer my variant a little bit only because I am, by character, a frugal (some might say, stingy;-) person... "waste not, want not"!-)

Python, Given a task in which substring needs to be removed from the end of the string. Given below are a few methods to solve the given task. Method #1: Using Naive  Home » Python » python: remove substring only at the end of string python: remove substring only at the end of string Posted by: admin January 4, 2018 Leave a comment

If speed is not important, use regex:

import re

somestring='this is some string rec'

somestring = re.sub(' rec$', '', somestring)

Python Remove Character from String, How do I remove a substring from a string in Python? Python Server Side Programming Programming If you want to remove a substring from the end of a string, you should fisrt check if the string ends with that substring. If it does, then slice the string keeping only the part without substring.

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

Strings - Learn Python 3, How do you remove the last part of a string in Python? Python | Remove the given substring from end of string. Sometimes we need to manipulate our string to remove extra information from string for better understanding and faster processing. Given a task in which substring needs to be removed from the end of the string. Given below are a few methods to solve the given task.

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)

Ways how to remove last character from String in Java, How do I remove the last character of a string? check a string for a substring where the end of the string loops around to the start Tag: python , python-2.7 So let's say I have a string, ' string ', and I know the length of the string, ' length '.

How to remove everything after a character in a string in Python, How do you remove all characters from a specific character in Python? The easiest way is probably just to split on your target word. my_string="hello python world , i'm a beginner " print my_string.split("world",1) [1] split takes the word (or character) to split on and optionally a limit to the number of splits. In this example split on "world" and limit it to only one split. improve this answer.

How do I remove a substring from the end of a string in Python?, in a string. Use str. split(sep, maxsplit) with maxsplit as 1 to split the string at the first occurrence of sep into a list. What you are trying to do is an extension of string slicing in Python: Say all strings are of length 10, last char to be removed: >>> st[:9] 'abcdefghi' To remove last N characters: >>> N = 3 >>> st[:-N] 'abcdefg'

How to Remove the Last Character of a String?, If you want to remove a substring from the end of a string, you should If it does, then slice the string keeping only the part without substring. I want to remove a substring from a string without any additional tabs/returns in the output string. Is there any method availaible or how can I do it. For the ease, I am giving an example: mainstr =""" ${if:isLeaf} Dont include this isLeaf=True ${/if:isLeaf} ${if:isStatic} include this isStatic=True ${/if:isStatic} """ Now if I want to remove :

Comments
  • possible duplicate of Python Remove last 3 characters of a string
  • possible duplicate of How do I remove a substring from the end of a string in Python?
  • @Jack, string is the name of a standard library module, that may also a bad idea to nameclash with, no less than a builtin...!-) Rather, I'd recommend you try getting used to employing identifiers such as thestring, astring, and the like, instead!-).
  • Is endswith a carry over from early implementations of str? It seems kind of redundant. def endswith(s, e): return s[-len(e):] == e
  • @Matt Joiner: I don't know. I'd suspect a convenience alias, given that words are easier for most people than reading slice notation.
  • Does the shadowing actually matter in this case? It only happens within the function call scope, right? So it's not going to cause problems unless someone expands the function in a way that requires the use of the original str or string, which seems unlikely in this case. Poor form maybe.. see also stackoverflow.com/a/2418007/210945 - string_ would be recommended by PEP8.
  • what do you have a space in the import a' 'a.xxx ?
  • @Blankman, it's a bash command running Python: the setup (-s) is one argument, the code being timed the other. Each is quoted so I don't have to worry about it including spaces and/or special character, os course. You always separate arguments with spaces in bash (and most other shells, including Windows' own cmd.exe, so I'm pretty surprised at your question!), and quoting arguments to a shell command to preserve spaces and special characters within each argument is also definitely not what I would call a peculiar, rare, or advanced usage of any shell...!-)
  • Oh I see you've bypassed endswith as I mentioned in Jack's answer. Caching the len also avoids Python's (and C's!) terrible call overhead.
  • I'm wondering what would be the performances if the regex where compiled only once and reused multiple times.
  • Capturing groups are be overkill here. sub(' rec$', '', str) works.
  • @JackKelly I like your comment better than your answer.
  • This does not always work. It will split at the string at all occurrences of ` rec` and return the first fragment. The prefix l and r only make a difference, if the separator string can overlap or a maximum number of splits is specified.