[英]Extend all occurences in a string in Python
目標是在源字符串中為所有出現的子字符串(不區分大小寫)添加前綴和后綴。 我基本上需要弄清楚如何從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'
就像是
import re
ar_re = re.compile("(ar)", re.I)
print ar_re.sub(r"[b]\1[/b]", "You ARe probably familiaR with wildcard")
也許?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.