Add trailing space to list of strings

I have a list of lines like this:

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

      

I want to basically concatenate these elements into one readable line. My logic is this:

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 in several different ways.

Using list comprehension:

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

      

State it (I think it's a little 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, "smarter" way to accomplish this?

+3


source to share


2 answers


>>> 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.'

      



+5


source


You can just understand the list using strip

:

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

      



It is also best not to call the list "list" since it is built-in.

+1


source







All Articles