你可以使用
string.Formatter.parse:
Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by vformat() to break the string into either literal text, or replacement fields.
The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None.
from string import Formatter
s = 'The value of x is {x}, and the list is {y} of len {}'
print([t[1] for t in Formatter().parse(s) if t[1]])
['x', 'y']
不确定这是如何真正帮助您尝试做的,因为您可以在函数中将x和y传递给str.format或使用** locals:
def somefunc():
x = 123
y = ['a', 'b']
print('The value of x is {x}, and the list is {y} of len {}'.format(len(y),**locals()))
如果要打印命名的args,可以添加Formatter输出:
def somefunc():
x = 123
y = ['a', 'b']
print("The named args are {}".format( [t[1] for t in Formatter().parse(s) if t[1]]))
print('The value of x is {x}, and the list is {y} of len {}'.format(len(y), **locals()))
哪个会输出:
The named args are ['x', 'y']
The value of x is 123, and the list is ['a', 'b'] of len 2