[英]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.我想把列表的这个值放到 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 """所以,my_string 将是: """ 你好,约翰,我想和你一起工作。我需要你的帮助来完成我的项目。问候,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?我怎样才能在 Python 中做到这一点? Thanks in advance.提前致谢。
With regex you can use re.sub
and lambada to pop
the items from the list使用正则表达式,您可以使用re.sub
和 lambda 来从列表中pop
项目
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.关于评论的编辑有时 [placeholder] 的 # 和列表的长度可能不相等。 : :
You can use empty string in the lambda
if the list is empty如果列表为空,您可以在lambda
使用空字符串
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.使用{}
而不是[placeholder]
会更好,因为它允许您将替换列表解压缩到默认str.format()
而无需任何额外修改。
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()
.如果不可能修改此“模板”,您可以使用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.如果占位符的数量可能大于my_lst
长度,您可以使用自定义格式化程序,它将返回一个默认值。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.