简体   繁体   中英

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.

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)

It'll be better to use {} instead of [placeholder] because it will allow you to unpack your list of replacements into default str.format() without any additional modifications.

my_string = """\
Hello {},

I would {} to work with you. I need your {} to complete my project.

Regards,
{}\
"""
my_lst = ['John', 'like', 'help', 'Doe']

my_string = my_string.format(*my_lst)

If modifying this "template" if not possible, you can do that programmatically using str.replace() .

my_string = my_string.replace("[placeholder]", "{}").format(*my_lst)

If amount of placeholders could be higher than length of my_lst , you may use a custom formatter which will return a default value.

from string import Formatter

class DefaultFormatter(Formatter):
    def __init__(self, default=""):
        self.default = default
    
    def get_value(self, key, args, kwargs):
        if isinstance(key, str) or key < len(args):
            return super().get_value(key, args, kwargs)
        else:
            return self.default

fmt = DefaultFormatter()
my_string = fmt.format(my_string.replace("[placeholder]", "{}"), *my_lst)

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