3

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?

2
  • 1
    What is not 'sane' about this? Commented Apr 3, 2012 at 0:03
  • Well, it's not exactly insane per se, but I could tell I was making things more difficult. Luckily Nolen found a good solution. Commented Apr 3, 2012 at 0:16

2 Answers 2

5
>>> 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.'
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! That makes a lot more sense. One question, why use rstrip() instead of strip()?
I originally used strip, but you had said that you were dealing with strings that "ended" in a space so I figured we only needed to strip off spaces on the right side / I didn't want to remove spaces on the left that were important. If I was wrong I'll gladly change it to strip.
In my script, I am getting these strings from a database (each row has part of the message). From what I've seen so far, the data is all kinds of messy. I think I'll be safe and use strip(), since the join should take care of spacing out the sentences after strip().
You should use a generator expression instead of a list comprehension to avoid making the temporary list. Just leave the [] out of the join
Reverted back to strip. Thanks for the tip @gnibbler, you are always on top of these things :D
1

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.

1 Comment

Good idea, I've changed the variable name in my original question. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.