的名單我有一個字符串列表如下:添加尾隨空格爲字符串
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