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

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

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

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

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

回答 0

字符串replace()函数可以完美解决此问题:

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

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

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

string replace() function perfectly solves this problem:

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.

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

回答 1

re.sub直接使用,可让您指定count

regex.sub('', url, 1)

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

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

regex.sub('', url, 1)

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