Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用值列表替换字符串中占位符的简单方法?_Python - Fatal编程技术网

Python 用值列表替换字符串中占位符的简单方法?

Python 用值列表替换字符串中占位符的简单方法?,python,Python,我有一个包含占位符的长字符串,应该用一些数据替换它 strOut = "text text {{ }} text text {{ }}" 用这个图案 pattern = r'\{{(.+?)\}}' 这样做对我来说很容易 pattern.sub(self.mymethod, strOut) 其中将调用mymethod进行替换。它实际上工作得很好。 然而,这是现在的问题。我需要用列表中的值替换字符串中的所有占位符。例如,这也是字符串: strOut = "text text {{ }} te

我有一个包含占位符的长字符串,应该用一些数据替换它

strOut = "text text {{ }} text text {{ }}"
用这个图案

pattern = r'\{{(.+?)\}}'
这样做对我来说很容易

pattern.sub(self.mymethod, strOut)
其中将调用mymethod进行替换。它实际上工作得很好。 然而,这是现在的问题。我需要用列表中的值替换字符串中的所有占位符。例如,这也是字符串:

strOut = "text text {{ }} text {{ }} text"
它将始终具有未确定数量的占位符。如果我还有一个列表,比如说2个值

myList = [2, 3]
我需要一种将这些值注入占位符的方法,并以这种方式结束

"text text 2 text 3 text"
列表中的值数和占位符数总是相同的,我只是不知道会有多少。

示例代码:

>>> strOut = "text text {{ }} text text {{ }}"
>>> pattern = r'\{{(.+?)\}}'
>>> import re
>>> re.findall(pattern, strOut)
[' ', ' ']
>>> items = iter(str(el) for el in [1, 2])
# as pointed out by @eyquem, this can also be written as:
# items = imap(str, [1, 2])

>>> re.sub(pattern, lambda L: next(items), strOut)
'text text 1 text text 2'
如果没有足够的参数满足占位符的要求,则会中断,否则忽略其余的参数

如果你使用的是2.7+,如果你可以不使用
{}
作为占位符,你就会笑,因为你可以使用
'text text text{}text{}。例如,格式(*[1,2])

和为了“乐趣”

(ab)使用lambda,您可以执行以下操作:

re.sub(pattern, lambda i, j=(str(el) for el in [1, 2]): next(j), strOut)

您可以尝试类似的方法(它使用
re.sub
count
参数):


如果在
strOut
文本中没有出现
'{}'
(与
'{}}'
相反),则以下方法有效。对于如图所示的
strOut
myList
,它生成的字符串是
“文本文本2文本3文本”

strOut = "text text {{ }} text {{ }} text"
myList = [2, 3]
strOut.replace('{{ }}','{}').format(*myList)
我喜欢这样做的原因如下:

  • 不再需要对值进行排序
  • 一次可以替换多个占位符

启发,您可以使用并传递带有参数解包(*)的列表


@出于好奇,你不能使用内置的
str.format
{}
作为占位符吗?@Jon Clements不是
iter(str(el)表示[1,2]中的el)
格式:
imap(str[1,2])
?@eyquem d0h!是的,我刚刚有了iter([1,2]),然后意识到它不能工作,所以就把它改成了发电机
strOut = "text text {{ }} text {{ }} text"
myList = [2, 3]
strOut.replace('{{ }}','{}').format(*myList)
my_csv = '%(first)s,%(last)s'
print my_csv % dict(last='Doe', first='John')  # John,Doe
>>> myList = [2, 3]
>>> strOut = 'text text {} text {} text'
>>> print(strOut.format(*myList))
text text 2 text 3 text