【发布时间】:2021-05-30 03:30:35
【问题描述】:
我有一个使用% 样式格式的字符串,我想从中提取其键:
s = 'Hello %(name)s, you are %(age)d years old!'
我想做一些事情,例如:
from string import Formatter
keys = {key for _, k, _, _ in Formatter().parse(s)}
print(keys)
# ('name', 'age')
但是,% 样式格式不支持此功能;还有其他方法吗?我也已经读过:
【问题讨论】:
-
re.findall(r'%\((\w+)\)', s)适用于给定的示例
标签: python