繁体   English   中英

在循环中串联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: [{}]'.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 ) )

您可以加入Estimators的成员:

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

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

由于没有提到的帖子对我有用(我总是得到'type'对象是不可迭代的,@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获取类的成员,因为它们以字典格式存储,然后过滤掉所有以__开头的成员,然后由于列表中的元素显示为字符串'我用空字符串替换了它们。

如果将我的解决方案与@SigveKolbeinson的答案结合在一起,则可以减少一些代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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