I have to substitute substrings in a string if such substring belong to a list
txt = 'lorem ipsum; lorem ipsum. lorem ipsum: loren lorem'
list_punctuation = [', ',': ','; ']
for punct in list_punctuation:
txt = txt.replace(punct,punct + '<<')
thats the tipical way. I loop through the elemtents of the list and make the substitution which consists on include a simbol "<<" after the punctuation.
The question is if there is a more pythonic way to do this. I dont like that loop and on top of being ugly it is probably very slow.
any idea?
EDIT1
Regex works. But I still think that there is a pythonic one liner without using external libraries (even if re is part of the standard one). Why do I refer a non-regex solution? because the list will be built separately and will change with the time. it is easier to change a list than the regex. I can not know now what the list will content. The punctuation list was a short example.
EDIT2 there are two links suggested in the answers.
a) the first one is about substitutions with conditions. There is no condition here, simply elements of a list. In this link a multiline solution is offer. My question is about finding a one liner. The aim of this question is finding a more concise solution.
How to replace multiple substrings of a string?
b) This question is about replacing characters and there is no reference to a list including the elements to substitute. in b) multiline coding is not a problem whereas here is exactly the problem. Best way to replace multiple characters in a string?
NOR a) or b) are solutions. But does not matter, this question was already blocked insisting in that there is a solution there.