delavnog delavnog - 5 months ago 16
Python Question

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 (
). Obviously (stupid me), because I have used lstrip wrongly: lstrip will remove all characters which appear in the passed
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?


I don't know about "standard way".

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