concatenating python strings in a loop
Question: I am using enums and string.join() method to form a help string in Python:

I have the following code segment:

    
    
    from enum import Enum
    
    class Estimators(Enum):
        rsac = 1
        msac = 2
    

Now, I create a help string as follows:

    
    
    est_help = 'Valid options are: [' + (str(i.name) + ', ' for i in Estimators) + ']'
    

This throws a TypeError exception as:

    
    
    TypeError: cannot concatenate 'str' and 'generator' objects
    

I was wondering what I am doing wrong. The `i.name` is of string type.


Answer: The error message tells you what you are doing wrong - attempting to
concatenate a string and a generator. What you want to do is to make a list
using list comprehension based on the generator, then use that

    
    
    est_help = 'Valid options are: [{}]'.format( ', '.join( i.name for i in Estimators))
    

Let's decompose this into individual steps:

  1. Create the list `[rsac,msac]`: `est_list = [str(i.name) for i in Estimators]`
  2. Create a string with the list elements separated by a comma `'rsac, msac'`: `est_str = ', '.join( est_list )`
  3. Insert the string into your text template: `est_help = 'Valid options are: [{}]'.format( est_str )`, and get the resulting string `Valid options are: [rsac, msac]'`

**edit: modified code incorporating suggestions from comments**

    
    
    est_help = 'Valid options are: [{}]'.format( ', '.join( i.name for i in Estimators ) )
    

