替换文本中最后一次出现的字符串

Cle*_*lee 5 python regex string replace

假设我有这段文字:

Saturday and Sunday and Monday and Tuesday and Wednesday and Thursday and Friday are days of the week.  
Run Code Online (Sandbox Code Playgroud)

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

Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday and Friday are days of the week. 
Run Code Online (Sandbox Code Playgroud)

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

Kev*_*uan 17

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

str.replace(old, new[, count])

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

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

str.count(sub[, start[, end]])

返回范围中子字符sub的非重叠出现次数[start, end].可选参数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.  '
Run Code Online (Sandbox Code Playgroud)