2
import re def bold_partial(long_string, partial): replacer = re.compile(partial, re.IGNORECASE) new_long_string = replacer.sub('<b>' + partial + '</b>', long_string) print new_long_string bold_partial('My name is Roger the Shrubber. I arrange, design, and sell shrubberies.', 'roger the shrubber') 

Returns:
My name is roger the shrubber. I arrange, design, and sell shrubberies.

I'd like to return the original case:

My name is Roger the Shrubber. I arrange, design, and sell shrubberies.

Sorry, but I'm a total noob. Any help would be greatly appreciated.

2 Answers 2

4
def bold_partial_rep(matchobj): return '<b>' + matchobj.group(0) + '</b>' def bold_partial(long_string, partial): replacer = re.compile(partial, re.IGNORECASE) new_long_string = replacer.sub(bold_partial_rep, long_string) print new_long_string 

Or if you want to shorten code you can get rid of the new function and use the following line in bold_partial():

new_long_string = replacer.sub(lambda m: '<b>%s</b>' % m.group(0), long_string) 
Sign up to request clarification or add additional context in comments.

Comments

0

Pass a function to .sub() that returns the appropriate replacement instead, or look at group #0.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.