【发布时间】:2012-04-16 15:27:40
【问题描述】:
我有一个这样的字符串列表:
my_list = ['Lorem ipsum dolor sit amet,', 'consectetur adipiscing elit. ', 'Mauris id enim nisi, ullamcorper malesuada magna.']
我想基本上将这些项目组合成一个可读的字符串。我的逻辑如下:
If the list item does not end with a space, add one
otherwise, leave it alone
Then combine them all into one string.
我能够通过几种不同的方式来实现这一点。
使用列表推导:
message = ["%s " % x if not x.endswith(' ') else x for x in my_list]
messageStr = ''.join(message)
拼写出来(我认为这更具可读性):
for i, v in enumerate(my_list):
if not v.endswith(' '):
my_list[i] = "%s " % v
messageStr = ''.join(my_list)
我的问题是,有没有更简单、“更理智”的方式来实现这一点?
【问题讨论】:
-
这有什么不“理智”的?
-
嗯,这本身并不完全是疯狂的,但我可以看出我让事情变得更加困难。幸运的是,Nolen 找到了一个很好的解决方案。
标签: python string list whitespace concatenation