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


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


source


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


source


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


source







All Articles