替换 Python 中第一次出现的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4628618/
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 16:36:50  来源:igfitidea点击:

Replace first occurrence of string in Python

pythonregex

提问by marks34

I have some sample string. How can I replace first occurrence of this string in a longer string with empty string?

我有一些示例字符串。如何用空字符串替换较长字符串中此字符串的第一次出现?

regex = re.compile('text')
match = regex.match(url)
if match:
    url = url.replace(regex, '')

采纳答案by virhilo

string replace()function perfectly solves this problem:

string replace()函数完美的解决了这个问题:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

string.replace(s, old, new[, maxreplace])

返回字符串 s 的副本,其中所有出现的子字符串 old 都被 new 替换。如果给出了可选参数 maxreplace,则替换第一个 maxreplace 出现。

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

回答by Konrad Rudolph

Use re.subdirectly, this allows you to specify a count:

re.sub直接使用,这允许您指定一个count

regex.sub('', url, 1)

(Note that the order of arguments is replacement, originalnot the opposite, as might be suspected.)

(请注意,参数的顺序是replacementoriginal而不是相反,这可能会被怀疑。)