替换 Python 中第一次出现的字符串 [英] Replace first occurrence of string in Python

查看:113
本文介绍了替换 Python 中第一次出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

regex = re.compile('text')匹配 = regex.match(url)如果匹配:url = url.replace(regex, '')

解决方案

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

<块引用>

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

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

<预><代码>>>>u'longlongTESTstringTEST'.replace('TEST', '?', 1)u'longlong?stringTEST'

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

解决方案

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'

这篇关于替换 Python 中第一次出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆