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

时间:2021-09-22 09:31:13

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, '')

2 个解决方案

#1


158  

string replace() function if perfectly solves this problem:

如果能够很好地解决这个问题:

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

字符串。替换(年代,旧的,新的[,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.

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

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

#2


12  

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

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

regex.sub('', url, 1)

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

(注意,参数的顺序是更换,原来不是相反的,可能会怀疑。)

#1


158  

string replace() function if perfectly solves this problem:

如果能够很好地解决这个问题:

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

字符串。替换(年代,旧的,新的[,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.

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

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

#2


12  

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

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

regex.sub('', url, 1)

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

(注意,参数的顺序是更换,原来不是相反的,可能会怀疑。)