简体   繁体   中英

Extend all occurences in a string in Python

The goal is to prefix and suffix all occurrences of a substring (case-insensitive) in a source string. I basically need to figure out how to get from source_str to 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'

In this example, I am finding all occurrences of 'ar' (case insensitive) and replacing each occurrence by (ie AR, aR and ar respectively), with a prefix ([b])and suffix ([/b]). 的前缀([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'

Something like

import re
ar_re = re.compile("(ar)", re.I)
print ar_re.sub(r"[b]\1[/b]", "You ARe probably familiaR with wildcard")

perhaps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM