Remove a prefix from a string


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:


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?

Answer rating: 270

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 and @Stefan, on Python 3.9+ you can use


with the same behavior.