简体   繁体   中英

Add trailing space to list of strings

I have a list of strings like this:

my_list = ['Lorem ipsum dolor sit amet,', 'consectetur adipiscing elit. ', 'Mauris id enim nisi, ullamcorper malesuada magna.']

I want to basically combine these items into one readable string. My logic is as follows:

If the list item does not end with a space, add one
otherwise, leave it alone
Then combine them all into one string.

I was able to accomplish this a few different ways.

Using a list comprehension:

message = ["%s " % x if not x.endswith(' ') else x for x in my_list]
messageStr = ''.join(message)

Spelling it out (I think this is a bit more readable):

for i, v in enumerate(my_list):
    if not v.endswith(' '):
        my_list[i] = "%s " % v
messageStr = ''.join(my_list)

My question is, is there an easier, "more sane" way of accomplishing this?

>>> my_list = ['Lorem ipsum dolor sit amet,', 'consectetur adipiscing elit. ', 'Mauris id en
im nisi, ullamcorper malesuada magna.']
>>> ' '.join(string.strip() for string in my_list)
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris id enim nisi, ullamcorper
 malesuada magna.'

You could simply the list comprehension a little by using strip :

' '.join([x.strip() for x in list])

It's also best not to call your list "list" as that is a built-in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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