learnpython.org modules exercise
Question: # Hello community,

**[ Preamble ] :**  
I come from a BASH scripting background _(still learning there as well)_ and
decided it might benefit my learning process by venturing into another
language. The natural choice for me seemed to be Python. I began studying a
bit and have been going through the exercises found on www.learnpython.org.
Particularly, [Modules and
Packages](http://www.learnpython.org/Modules%20and%20Packages).

**[ Problem ] :**

`Import` the module **re** and `print` out alphabetically **sorted** , all
functions in the module that contain the word `find`.

**[ Tried ] :**

    
    
    # import the module.
    import re
    
    # store output of dir(re) in reLST as string list.
    ''' I believe that's what happens, correct? '''
    reLST = dir(re)
    
    # iterate over reLST and assign m strings matching word containing find.
    for element in reLST:
        m = re.match("(find\w+)", element)
    
    # Here it prints out the matches, but only using the function .groups()
    ''' Won't work using print sorted(m)  ---why? '''
    # Found tutorial online, but no real understanding of .groups() function use.     
        if m:
            print sorted(m.groups())
    

**[ Expected Output ] :**  
['findall', 'finditer']

**[ My Output ] :**  
['findall']  
['finditer']

**[ Question ] :**  
Technically, the code works and does output all _strings_ grabbed from
`dir(re)`, but on a new line. I'm guessing this is done as part of the
`.groups()` function? What would be a good way of getting the desired output
in the correct format?


Answer: You should collect the results in a list, and then sort them:

    
    
    import re
    
    
    results = []
    for element in dir(re):
        m = re.match("(find\w+)", element)
        if m:
            results.append(m.group(1))
    
    print sorted(results)
    

Also, instead of `re`, you can use `startswith()`:

    
    
    import re
    
    
    results = []
    for element in dir(re):
        if element.startswith('find'):
            results.append(element)
    
    print sorted(results)
    

or, the same thing in one line using `list comprehension`:

    
    
    import re
    
    print sorted([element for element in dir(re) if element.startswith('find')])
    

If the word `find` can be anywhere in the string, you should use `in` instead
of `startswith()`:

    
    
    import re
    
    print sorted([element for element in dir(re) if 'find' in element])
    

