的名单我有一个字符串列表如下:添加尾随空格为字符串
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)
拼写出来(我认为这是一个有点更具可读性):
3210我的问题是,有更简单的,“更理智”完成这个的方法?
这是什么不“理智”? – 2012-04-03 00:03:22
那么,它本身并不是疯狂的,但我可以告诉我让事情变得更加困难。幸运的是Nolen找到了一个好的解决方案。 – Nitzle 2012-04-03 00:16:21