I want to parse a string to extract all the substrings in curly braces:
'The value of x is {x}, and the list is {y} of len {}'
should produce:
(x, y)
Then I want to format the string to print the initial string with the values:
str.format('The value of x is {x}, and the list is {y} of len {}', x, y, len(y))
How can I do that?
Example usage:
def somefunc():
x = 123
y = ['a', 'b']
MyFormat('The value of x is {x}, and the list is {y} of len {}',len(y))
output:
The value of x is 123, and the list is ['a', 'b'] of len 2
You can use string.Formatter.parse:
Not sure how that really helps what you are trying to do as you can just pass x and y to str.format in your function or use **locals:
If you wanted to print the named args you could add the Formatter output:
Which would output: