查找用于替换字符串的所有替换名称

Find all substitution names which are used for substitution in string

我有用于格式化名称替换变量的模板字符串,例如

mystr = "Some {title} text {body}"
mystr_ready = mystr.format(title='abc', body='bcd')

那里的{}可以有很多不同的替换变量名,我们每次都不知道它们的名字,所以在从数据库中取出它们进行替换之前,我需要先知道它们的名字(取所有数据库中巨大 table 的变体太慢了)。

所以我需要实现这个逻辑:

mystr = "Some {title} text {body}"
subs = SOMETHING(mystr)  # title, body

我知道这可以用正则表达式解决,但我想可以有更优雅和 pythonic 的解决方案。

使用string.Formatter:

import string

parser = string.Formatter().parse

def fmt_fields(fmt):
    return [f[1] for f in parser(fmt) if f[1] is not None]

print(fmt_fields("Some {title} text {body}"))