我有一个包含%(name)s
占位符的字符串,我想获取所有名称,例如:This is a %(name)s example string %(foo)s I would like %(bar)s to extract all the placeholders from %(place)s
我想要一个包含name
,foo
,bar
,place
答案 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']
%\((.+?)\)
的意思是从%(
开始,到下一个)
结束,捕获之间的所有内容。