Skip to content
Advertisement

Search in string and replace with a value from a list in python using regex

my_string = """"
Hello [placeholder],

I would [placeholder] to work with you. I need your [placeholder] to complete my project.

Regards,
[placeholder]
"""

my_lst = ['John', 'like', 'help', 'Doe']

I want to put this value of the list into my_string.

So, my_string would be: “”” Hello John, I would like to work with you. I need your help to complete my project. Regards, Doe “””

Here, number of [placeholder] and length of the list would be dynamic. So, I need a dynamic solution. That will work for any string regardless number of [placeholder] and length of list. How can I do this in Python? Thanks in advance.

Advertisement

Answer

With regex you can use re.sub and lambada to pop the items from the list

my_string = re.sub(r'[(.*?)]', lambda x: my_lst.pop(0), my_string)

Edit regarding the comment sometimes # of [placeholder] and length of the list may not equal.:

You can use empty string in the lambda if the list is empty

my_string = re.sub(r'[(.*?)]', lambda x: my_lst.pop(0) if my_lst else '', my_string)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement