[英]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))
让我们将其分解为各个步骤:
[rsac,msac]
: est_list = [str(i.name) for i in Estimators]
'rsac, msac'
分隔的字符串: est_str = ', '.join( est_list )
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.