Advanced string replacements in python

半世苍凉 提交于 2021-02-11 18:12:35

问题


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?


回答1:


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!'



回答2:


for i in dictionary.keys():
    string.replace('<'+i+'>',dictionary[i]]


来源:https://stackoverflow.com/questions/26844742/advanced-string-replacements-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!