Remove a prefix from a string [duplicate]
Sophia Terry
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:
xtensionsWhich 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?
36 Answers
I don't know about "standard way".
def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] return text # or whateverAs noted by @Boris and @Stefan, on Python 3.9+ you can use
text.removeprefix(prefix)with the same behavior.
4Short and sweet:
def remove_prefix(text, prefix): return text[text.startswith(prefix) and len(prefix):] 12 What about this (a bit late):
def remove_prefix(s, prefix): return s[len(prefix):] if s.startswith(prefix) else s 2 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 1 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 0 def remove_prefix(str, prefix): if str.startswith(prefix): return str[len(prefix):] else: return strAs an aside note, str is a bad name for a variable because it shadows the str type.