问题:替换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

直接使用,可让您指定count

regex.sub('', url, 1)

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

Use 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.)


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。