替换 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
Replace first occurrence of string in Python
提问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'

