首页 文章

替换但是文本中最后一次出现的字符串[重复]

提问于
浏览
5

这个问题在这里已有答案:

假设我有这段文字:

Saturday and Sunday and Monday and Tuesday and Wednesday and Thursday and Friday are days of the week.

我希望除了最后一个 and 之外的所有内容都用逗号代替:

Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday and Friday are days of the week.

在正则表达式中有一种简单的方法吗?据我所知,正则表达式中的 replace 方法一直替换字符串 .

2 回答

  • 16

    str.replace()方法有一个 count 参数:

    str.replace(old,new [,count])返回字符串的副本,其中所有出现的substring old都替换为new . 如果给出可选参数计数,则仅替换第一次计数 .

    然后,使用str.count()检查字符串中有多少 and 然后 -1 (因为你需要最后的 and ):

    str.count(sub [,start [,end]])返回[start,end]范围内substring sub的非重叠出现次数 . 可选参数start和end被解释为切片表示法 .

    演示:

    >>> string = 'Saturday and Sunday and Monday and Tuesday and Wednesday and Thursday and Friday are days of the week.'   
    >>> string.replace(' and ', ", ", (string.count(' and ')-1))
    'Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday and Friday are days of the week.  '
    
  • 4

    如果你想要一个正则表达式解决方案,你可以匹配所有 and ,后面跟着另一个字符串 .

    >>> str='Monday and Tuesday and Wednesday and Thursday and Friday and Saturday and Sunday are the days of the week.'
    >>> import re
    >>> re.sub(' and (?=.* and )', ', ', str)
    'Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday are the days of the week.'
    

    (?= ... ) 是一个先行,它确保在字符串中稍后匹配,而不在实际匹配中包含它(因此也不在替换中) . 这有点像比赛的条件 .

相关问题