Python 从字符串中删除前缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16891340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:56:29  来源:igfitidea点击:

Remove a prefix from a string

python

提问by blueFast

I am trying to do the following, in a clear pythonic way:

我正在尝试以清晰的pythonic方式执行以下操作:

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 lstripwrongly: lstrip will remove all characters which appear in the passed charsstring, not considering that string as a real string, but as "a set of characters to remove from the beginning of the string".

这不是我所期望的(extensions)。显然(愚蠢的我),因为我错误地使用了lstrip: lstrip 将删除出现在传递的chars字符串中的所有字符,而不是将该字符串视为真正的字符串,而是将其视为“要从字符串开头删除的一组字符” .

Is there a standard way to remove a substring from the beginning of a string?

是否有从字符串开头删除子字符串的标准方法?

采纳答案by Elazar

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 @Stefan, in Python 3.9+ you can use text.removeprefix(prefix)with the same behavior.

正如@Stefan 所指出的,在 Python 3.9+ 中,您可以使用text.removeprefix(prefix)相同的行为。

回答by jamylak

regex solution (The best way is the solution by @Elazar this is just for fun)

正则表达式解决方案(最好的方法是@Elazar 的解决方案,这只是为了好玩)

import re
def remove_prefix(text, prefix):
    return re.sub(r'^{0}'.format(re.escape(prefix)), '', text)

>>> print remove_prefix('template.extensions', 'template.')
extensions

回答by mshsayem

What about this (a bit late):

这个怎么样(有点晚了):

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

回答by Zacrath

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

As an aside note, stris a bad name for a variable because it shadows the strtype.

顺便说str一句,对于变量来说是一个不好的名字,因为它遮蔽了str类型。

回答by Blckknght

I think you can use methods of the strtype to do this. There's no need for regular expressions:

我认为您可以使用该str类型的方法来执行此操作。不需要正则表达式:

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

回答by martineau

Short and sweet:

简短而甜蜜:

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