Remove a prefix from a string [duplicate]

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

text.removeprefix(prefix)

In older versions you can use with the same behavior:

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

Leave a Comment