在python中获取所有%(name)s占位符

时间:2019-10-31 10:34:58

标签: python-3.x

我有一个包含%(name)s占位符的字符串,我想获取所有名称,例如:This is a %(name)s example string %(foo)s I would like %(bar)s to extract all the placeholders from %(place)s

我想要一个包含namefoobarplace

的列表

2 个答案:

答案 0 :(得分:2)

使用正则表达式。

例如:

import re

s = "This is a %(name)s example string %(foo)s I would like %(bar)s to extract all the placeholders from %(place)s"
print(re.findall(r"%\((.*?)\)", s))
# --> ['name', 'foo', 'bar', 'place']

答案 1 :(得分:1)

似乎是re.findall的好用法

>>> import re
>>> string = "This is a %(name)s example string %(foo)s I would like %(bar)s to extract all the placeholders from %(place)s"
>>> re.findall(r'%\((.+?)\)', string)
['name', 'foo', 'bar', 'place']

%\((.+?)\)的意思是从%(开始,到下一个)结束,捕获之间的所有内容。

相关问题