List of variables within a string
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 output
['a', 'b', 'c', 'a']
+3
scls
source
to share
3 answers
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']
+6
falsetru
source
to share
You can use regex
(?<={)\w+(?=})
Usage example
>>> import re
>>> s="{a}|{b}.{c}.{a}"
>>> re.findall(r'(?<={)\w+(?=})', s)
['a', 'b', 'c', 'a']
Regex
-
(?<={)
peek, claims regex is given{
-
\w+
matches a variable name -
(?=})
look ahead asserts regex if follow}
+1
nu11p01n73R
source
to share
If your variable is a single alphanumeric character try:
>>> s="{a}|{b}.{c}.{a}"
>>> [c for c in s if c.isalnum()]
['a', 'b', 'c', 'a']
0
alvas
source
to share