在循环中连接 python 个字符串

concatenating python strings in a loop

我正在使用枚举和 string.join() 方法在 Python:

中形成帮助字符串

我有以下代码段:

from enum import Enum

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

现在,我创建一个帮助字符串如下:

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

这将引发 TypeError 异常:

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

我想知道我做错了什么。 i.name是字符串类型。

解决方案

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

您可以加​​入 Estimators 的成员:

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

因为 none 提到的帖子对我有用(我总是得到 'type' object is not iterable,@lvc 弄明白了,我有 PyPI 的枚举,它没有内置的迭代器函数)这是我对问题的解决方案

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

我使用 vars 获取 class 的成员,因为它们以字典格式存储,然后过滤掉所有以 __ 开头的成员,然后因为列表的元素出现作为 ' 的字符串,我用空字符串替换它们。

如果我像这样将我的解决方案与@SigveKolbeinson 的回答结合起来,可以减少一些代码

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

错误消息告诉您做错了什么 - 试图连接字符串和生成器。你想要做的是使用基于生成器的列表理解来制作一个列表,然后使用那个

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

让我们将其分解为单独的步骤:

  1. 创建列表[rsac,msac]est_list = [str(i.name) for i in Estimators]
  2. 用逗号分隔的列表元素创建一个字符串'rsac, msac'est_str = ', '.join( est_list )
  3. 将字符串插入您的文本模板:est_help = 'Valid options are: [{}]'.format( est_str ),并获取生成的字符串 Valid options are: [rsac, msac]'

编辑:修改后的代码合并了评论中的建议

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