假设我有这段文字:
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
方法一直在替换字符串。
答案 0 :(得分:17)
str.replace()
方法有一个count
参数:
str.replace(old, new[, count])
返回字符串的副本,其中所有出现的substring old都替换为new。如果给出了可选参数计数,则仅替换第一次计数出现次数。
然后,使用str.count()
检查字符串中and
的数量,然后-1
(因为您需要最后一个and
):
str.count(sub[, start[, end]])
返回
[start, end]
范围内子串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. '
答案 1 :(得分:4)
如果你想要一个正则表达式解决方案,你可以匹配所有and
s后面的字符串中的另一个>>> 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.'
。
(?=
)
... 8.8.8.8
是一个先行,它确保在字符串中稍后匹配,而不在实际匹配中包含它(因此也不在替换中)。这有点像比赛的条件。