0

I have some strings in a python script, they look like

<tag1> thisIsSomeText <otherTag>, <tag1>!

I want to parse these lines, and replace every tag by a string from a dictionary.

Assume my dict looks like:

tag1: Hello
otherTag: Goodbye

Then the output line should look like:

Hello thisIsSomeText Goodbye, Hello!

As one can see, the tags (and its braces) are replaced. Multiple occurences are possible.

In C, I would search for '<', remember its position, search for the '>', do some ugly string manipulation... But i guess, Python has better solutions for this.

Maybe Regex? Well, I hope my task is simple enough that I could be solved without regex. But I have no plan how to start in Python. Any suggestions?

falsetru
  • 357,413
  • 63
  • 732
  • 636
lugge86
  • 255
  • 3
  • 11
  • You want a [template engine](http://jinja.pocoo.org/) or [string formatting](https://docs.python.org/2/library/stdtypes.html#str.format). – ThiefMaster Nov 10 '14 at 13:25

2 Answers2

4

re.sub accepts not only string, but also a function as a replacement as the second parameter. The function accepts a match object, and the return value of the function is used a replacement string.

>>> import re
>>> mapping = {'tag1': 'Hello', 'otherTag': 'Goodbye'}
>>> re.sub(r'<(\w+)>', lambda m: mapping[m.group(1)],
...        '<tag1> thisIsSomeText <otherTag>, <tag1>!')
'Hello thisIsSomeText Goodbye, Hello!'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • @falsetrue: I guess your solution is better than the above. However, i couldn't get it working out of the box. So I ended up with the solution from greato, as this was working (after fixing the known issues).... As I'm writing this, I think i found the issue. Reassigning is also necessary, right? – lugge86 Nov 10 '14 at 15:03
  • @lugge86, Could you explain how my solution does not work? Was there any error? If it had, please share me the traceback. – falsetru Nov 10 '14 at 15:04
  • @lugge86, Yes, you need reassignment. – falsetru Nov 10 '14 at 15:04
  • @lugge86, My answer will raise an exception if there's a tag which is not defined in the dictionary. To leave such word as is: use `dict.get` instead of `dict[..]`: `lambda m: mapping.get(m.group(1), m.group(0))` or or `lambda m: mapping.get(m.group(1), m.group(1))` according to your need. – falsetru Nov 10 '14 at 15:06
0
for i in dictionary.keys():
    string.replace('<'+i+'>',dictionary[i]]
Ricky Han
  • 1,309
  • 1
  • 15
  • 25