python - How to preserve case using re.IGNORECASE and .sub? -


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 roger shrubber. arrange, design, , sell shrubberies.', 'roger shrubber') 

returns:
name roger shrubber. arrange, design, , sell shrubberies.

i'd return original case:

my name roger shrubber. arrange, design, , sell shrubberies.

sorry, i'm total noob. appreciated.

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 want shorten code can rid of new function , use following line in bold_partial():

new_long_string = replacer.sub(lambda m: '<b>%s</b>' % m.group(0), long_string) 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -