Py学习  »  Python

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

TheDarkLord • 6 年前 • 2122 次点击  

%(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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54855
文章 [ 2 ]  |  最新文章 6 年前
khelwood
Reply   •   1 楼
khelwood    6 年前

似乎是个很好的用途 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']

%\((.+?)\) %( ,以下一个结尾 ) ,捕获中间的所有内容。

Rakesh
Reply   •   2 楼
Rakesh    6 年前

使用正则表达式。

前任:

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']