Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 442
scls Avatar asked Apr 10 '26 23:04

scls


2 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']
like image 151
falsetru Avatar answered Apr 13 '26 12:04

falsetru


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 }

like image 38
nu11p01n73R Avatar answered Apr 13 '26 13:04

nu11p01n73R