Python provides string formatting like
s="{a}|{b}.{c}.{a}"
s.format(a=2, b=3, c=4)
which outputs
'2|3.4.2'
I'm looking for a way to get a list of "variables" inside a string.
So in my example
list_of_var(s)
should outputs
['a', 'b', 'c', 'a']
Using string.Formatter.parse:
>>> s = "{a}|{b}.{c}.{a}"
>>> import string
>>> formatter = string.Formatter()
>>> [item[1] for item in formatter.parse(s)]
['a', 'b', 'c', 'a']
You can use the regex
(?<={)\w+(?=})
Example usage
>>> import re
>>> s="{a}|{b}.{c}.{a}"
>>> re.findall(r'(?<={)\w+(?=})', s)
['a', 'b', 'c', 'a']
Regex
(?<={) look behind, asserts the regex is presceded by {
\w+ matches the variable name
(?=}) look ahead asserts the regex if followed by }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With