The Python Oracle

Remove a prefix from a string

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping

--

Chapters
00:00 Question
00:53 Accepted answer (Score 368)
01:15 Answer 2 (Score 71)
01:29 Answer 3 (Score 54)
01:44 Answer 4 (Score 17)
02:03 Thank you

--

Full question
https://stackoverflow.com/questions/1689...

Question links:
[lstrip]: http://docs.python.org/2/library/string....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 452


For Python 3.9+:

text.removeprefix(prefix)

For older versions, the following provides the same behavior:

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



ANSWER 2

Score 54


What about this (a bit late):

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



ANSWER 3

Score 19


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



ANSWER 4

Score 18


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