社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

TheDarkLord • 6 年前 • 2125 次点击  

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