Remove a prefix from a string

Question:

I am trying to do the following, in a clear pythonic way:

def remove_prefix(str, prefix):
    return str.lstrip(prefix)

print remove_prefix('template.extensions', 'template.')

This gives:

xtensions

Which is not what I was expecting (extensions). Obviously (stupid me), because I have used lstrip wrongly: lstrip will remove all characters which appear in the passed chars string, not considering that string as a real string, but as “a set of characters to remove from the beginning of the string”.

Is there a standard way to remove a substring from the beginning of a string?

Asked By: blueFast

||

Answers:

regex solution (The best way is the solution by @Elazar this is just for fun)

import re
def remove_prefix(text, prefix):
    return re.sub(r'^{0}'.format(re.escape(prefix)), '', text)

>>> print remove_prefix('template.extensions', 'template.')
extensions
Answered By: jamylak

I don’t know about "standard way".

def remove_prefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    return text  # or whatever

As noted by @Boris-Verkhovskiy and @Stefan, on Python 3.9+ you can use

text.removeprefix(prefix)

with the same behavior.

Answered By: Elazar

What about this (a bit late):

def remove_prefix(s, prefix):
    return s[len(prefix):] if s.startswith(prefix) else s
Answered By: mshsayem
def remove_prefix(s, prefix):
    if s.startswith(prefix):
        return s[len(prefix):]
    else:
        return s
Answered By: Zacrath

I think you can use methods of the str type to do this. There’s no need for regular expressions:

def remove_prefix(text, prefix):
    if text.startswith(prefix): # only modify the text if it starts with the prefix
         text = text.replace(prefix, "", 1) # remove one instance of prefix
    return text
Answered By: Blckknght

Short and sweet:

def remove_prefix(text, prefix):
    return text[text.startswith(prefix) and len(prefix):]
Answered By: martineau
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.