简体   繁体   中英

Advanced string replacements in python

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?

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!'
for i in dictionary.keys():
    string.replace('<'+i+'>',dictionary[i]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM