The Python Oracle

Remove a prefix from a string

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping

--

Chapters
00:00 Remove A Prefix From A String
00:39 Accepted Answer Score 434
00:55 Answer 2 Score 74
01:06 Answer 3 Score 54
01:17 Answer 4 Score 17
01:31 Answer 5 Score 17
01:46 Thank you

--

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

--

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