Remove a prefix from a string

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

text.removeprefix(prefix)

with the same behavior.

Solution 2 - Python

Short and sweet:

def remove_prefix(text, prefix):
    return text[text.startswith(prefix) and len(prefix):]

Solution 3 - Python

What about this (a bit late):

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

Solution 4 - Python

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

Solution 5 - Python

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

Solution 6 - Python

def remove_prefix(str, prefix):
    if str.startswith(prefix):
        return str[len(prefix):]
    else:
        return str

As an aside note, str is a bad name for a variable because it shadows the str type.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionblueFastView Question on Stackoverflow
Solution 1 - PythonElazarView Answer on Stackoverflow
Solution 2 - PythonmartineauView Answer on Stackoverflow
Solution 3 - PythonmshsayemView Answer on Stackoverflow
Solution 4 - PythonjamylakView Answer on Stackoverflow
Solution 5 - PythonBlckknghtView Answer on Stackoverflow
Solution 6 - PythonZacrathView Answer on Stackoverflow