本文介绍了替换 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:

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

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

08-12 12:04