qhf*_*gva 9 python string python-2.x
给定格式化字符串:
x = "hello %(foo)s there %(bar)s"
Run Code Online (Sandbox Code Playgroud)
有没有办法获取格式变量的名称?(不自己直接解析它们).
使用正则表达式不会太难,但我想知道是否有更直接的方法来获得这些.
使用dict带有重写__missing__方法的子类,然后从中可以收集所有缺少的格式变量:
class StringFormatVarsCollector(dict):
def __init__(self, *args, **kwargs):
self.format_vars = []
def __missing__(self, k):
self.format_vars.append(k)
...
def get_format_vars(s):
d = StringFormatVarsCollector()
s % d
return d.format_vars
...
>>> get_format_vars("hello %(foo)s there %(bar)s")
['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)
如果您不想解析字符串,可以使用这个小函数:
def find_format_vars(string):
vars= {}
while True:
try:
string%vars
break
except KeyError as e:
vars[e.message]= ''
return vars.keys()
Run Code Online (Sandbox Code Playgroud)
>>> print find_format_vars("hello %(foo)s there %(bar)s")
['foo', 'bar']