3

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]).

2 Answers 2

4
>>> 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'
Sign up to request clarification or add additional context in comments.

Comments

3

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.