JavaScript
x
11
11
1
my_string = """"
2
Hello [placeholder],
3
4
I would [placeholder] to work with you. I need your [placeholder] to complete my project.
5
6
Regards,
7
[placeholder]
8
"""
9
10
my_lst = ['John', 'like', 'help', 'Doe']
11
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
JavaScript
1
2
1
my_string = re.sub(r'[(.*?)]', lambda x: my_lst.pop(0), my_string)
2
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
JavaScript
1
2
1
my_string = re.sub(r'[(.*?)]', lambda x: my_lst.pop(0) if my_lst else '', my_string)
2