Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 itself (i.e. AR, aR and ar respectively), with a prefix ([b])and suffix ([/b]).

like image 209
bmichel Avatar asked Sep 08 '26 08:09

bmichel


1 Answers

>>> 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'
like image 70
Shawn Chin Avatar answered Sep 10 '26 23:09

Shawn Chin