views:

107

answers:

1

This question falls into the "yes - this works, yes - this is ugly, yes - there is probably a better way" category. I want to use a regular expression to pull groups out of a match and then print the group number and the group value. It is to show someone how regular expressions work and to keep track of the values of each group. The code that works is:

import re

FundTypeGroups = re.match("([A-Z]0)(\d)([A-Z])","G02A").groups()
print FundTypeGroups

for FundTypeGroup in FundTypeGroups:
    print "%s: %s" % (FundTypeGroups.index(FundTypeGroup), FundTypeGroup)

Is there a better way to print the index of each tuple entry?

+4  A: 
 for index, group in enumerate(FundTypeGroups):
     print "%s: %s" % (index, group)

(and the variables should not start with a capital letter...)

KennyTM
If I change the string from "G02A" to something that doesn't match the pattern and no groups are returned, would I then add "except AttributeError" to catch this condition?
Count Boxer
@Count: Yes, or check if `FundTypeGroups` is None before looping.
KennyTM