0

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?

2
  • 4
    Never use capital letters as the first letter of a variable unless it refers to a class. Commented Mar 17, 2010 at 18:26
  • Instead of you hitting each style faux paux one at a time look at pep 8 for style guidance. python.org/dev/peps/pep-0008 Commented Mar 18, 2010 at 0:26

1 Answer 1

3
 for index, group in enumerate(FundTypeGroups):
     print "%s: %s" % (index, group)

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

Sign up to request clarification or add additional context in comments.

2 Comments

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: Yes, or check if FundTypeGroups is None before looping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.