scls
scls

Reputation: 17607

List of variable inside 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 outputs

['a', 'b', 'c', 'a']

Upvotes: 3

Views: 64

Answers (3)

nu11p01n73R
nu11p01n73R

Reputation: 26667

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 }

Upvotes: 1

alvas
alvas

Reputation: 122022

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']

Upvotes: 0

falsetru
falsetru

Reputation: 369034

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']

Upvotes: 6

Related Questions