简体   繁体   中英

concatenating python strings in a loop

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.

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 ) )

您可以加入Estimators的成员:

'Valid options are: [%s]' % ', '.join(Estimators.__members__)

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

Since none of the posts mentioned yet work for me(I always get 'type' object is not iterable, @lvc figured it out, I had the enum from PyPI which doesn't have the iterator function built in) here is my solution to the problem

from enum import Enum

class Estimators(Enum):
    rsac = 1
    msac = 2

e = Estimators
attributes = [attr for attr in vars(e) if not attr.startswith('__')]

est_help = 'Valid options are: ' + str(attributes).replace('\'','')

print est_help

I get the members of the class using vars since they are stored in dictionary format and then filter out all the members that start with __ and then since the elements of the list show up as strings with ' I replace those with an empty string.

Some of the code can be reduced if I combine my solution with @SigveKolbeinson's answer like so

est_help = 'Valid options are: [{}]'.format( ', '.join( [str(i) for i in vars(Estimators) if not i.startswith('__')]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM