目标是在源字符串中为所有出现的子字符串(不区分大小写)添加前缀和后缀.我基本上需要弄清楚如何从source_str到target_str.
source_str = 'You ARe probably familiaR with wildcard'
target_str = 'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'
在这个例子中,我发现所有出现的’ar'(不区分大小写)并且用自己的前缀([b])和后缀([/ b])替换每次出现(即AR,aR和ar).
最佳答案
>>> import re
>>> source_str = 'You ARe probably familiaR with wildcard'
>>> re.sub(r"(ar)", r"[b]\1[/b]", source_str, flags=re.IGNORECASE)
'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'