Is there a reverse operator to the '%' operator on string ?

hamish_lawson hamish_lawson at yahoo.co.uk
Thu Feb 14 17:26:39 CET 2002


Carel Fellinger wrote:

> Boris Boutillier wrote:

> I want to get the dictionary from the name and the Format something 
> like ...
> 'w%(width)dn%(nWord)d_%(fileName)s' op "w16n12_Toto" 
> which will give {'width':16,'nWord':12,'fileName': 'Toto'}

> What about regex's, like:
> 
> >>> import re
> >>> matcher = re.compile(r"^w(\d+)n(\d+)_(.*)$").match
> >>> matcher("w16n12_Toto").groups()
> ('16', '12', 'Toto')

Adding named groups to Carel's code gives you a dictionary of the 
matches:

>>> import re
>>> pattern = r"^w(?P<width>\d+)n(?P<nWord>\d+)_(?P<fileName>.*)$"
>>> matcher = re.compile(pattern).match
>>> matcher("w16n12_Toto").groupdict()
{'width': '16', 'nWord': '12', 'fileName': 'Toto'}


Hamish Lawson






More information about the Python-list mailing list