Weier
Weier

Reputation: 1429

Python: get string parameters

I'd like to transform a string expecting a dict of parameters to the list of keys of the expected dict, e.g. find f such that:

f("some text %(foo)s %(bar)s") == ['foo', 'bar',] # True

Is there some way to do it ?

Upvotes: 0

Views: 228

Answers (2)

seriyPS
seriyPS

Reputation: 7102

Smth like

>>> import re
>>> re.findall("%\(([^\)]+)\)[sif]", "some text %(foo)s %(bar)s", re.M)
['foo', 'bar']

[sif] part can be extended with symbols from table on http://docs.python.org/library/stdtypes.html#string-formatting-operations

Upvotes: 1

UltraInstinct
UltraInstinct

Reputation: 44444

How about this:

>>> S = "some text %(foo)s %(bar)s"
>>> print re.findall(r'%\((.*?)\)', S)
['foo', 'bar']

Upvotes: 0

Related Questions