开发者

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

I have a long string (a "template") containing "replacement points" in the form of %MARK% (there can be more occurences in the string for a single given marker too). I want to replace these markers, controlled by a Python dictionary (it does not contain the % signs for markers), like:

rep_dict = { "TITLE": "This is my title", "CONTENT": "Here it is the content" }

The problem: simple call of replace() method one by one is not a good solution: the previous replacement may contain one of these marks, which then must not be replaced!

The solution sh开发者_如何学Could be fast enough, since I have large templates, and I need to replace many of them within a big loop. I have a very ugly and long implementation with many find()'s, counting offsets in the original string during the replacament process, etc. I have the hope that there is a much nicer, more compact, and quicker solution.


The easiest solution is

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

Not fast enough? Someone said 'do not use regex' and you obey? Parsing your template using some code in Python would be even more complex and slow (don't forget, re is written in C).


This was excellent. I have always used the excuse of not having time to learn RegEx, but always respected it. This post gave me the necessary to get started. This was my solution though, I found the group call was mixed up in the dictionary parameters:

retVal          = re.sub(r'%title', theTitle, template)
retVal          = re.sub(r'%([a-z]+?)+', \
                    lambda m: myDict.get(m.group(0)[1:], ''), retVal)

title was not in the dictionary, that is why I did it first. Requrements of the others in the team.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜