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

mar*_*s34 98 python regex

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

regex = re.compile('text')
match = regex.match(url)
if match:
    url = url.replace(regex, '')
Run Code Online (Sandbox Code Playgroud)

vir*_*ilo 214

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

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

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

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
Run Code Online (Sandbox Code Playgroud)


Kon*_*lph 17

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

regex.sub('', url, 1)
Run Code Online (Sandbox Code Playgroud)

(注意参数的顺序replacement,original而不是相反,因为可能会被怀疑.)