How can I replace sub-strings of a large string based on a dictionary in Python? -


i have long string (a "template") containing "replacement points" in form of %mark% (there can more occurences in string single given marker too). want replace these markers, controlled python dictionary (it not contain % signs markers), like:

rep_dict = { "title": "this title", "content": "here content" } 

the problem: simple call of replace() method 1 one not solution: previous replacement may contain 1 of these marks, must not replaced!

the solution should fast enough, since have large templates, , need replace many of them within big loop. have ugly , long implementation many find()'s, counting offsets in original string during replacament process, etc. have hope there nicer, more compact, , quicker solution.

the easiest solution is

import re re.sub(r'%(.+?)%', lambda m: rep_dict[m.group(1)], your_template) 

not fast enough? said 'do not use regex' , obey? parsing template using code in python more complex , slow (don't forget, re written in c).


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -