0

I have a list of strings:

['Hello Yes', 'Good Now Order', 'Been There Before', 'Because']

I want to rewrite this as:

['Hello\nYes', 'Good\nNow\nOrder', 'Been\nThere\nBefore', 'Because']

So the \n goes into every space except the beginning or end of the string.

I have tried .split(' ') inside a for loop, but that gets messy and then unsure how to rejoin at the end.

1
  • 3
    Hint: Look at str.replace Commented Jul 25, 2018 at 23:04

3 Answers 3

5

You can try the following comprehension that uses the split and join approach you are suggesting:

l = ['Hello Yes', 'Good Now Order', 'Been There Before', 'Because']
l_new = ['\n'.join(s.split()) for s in l]  
# this would replace any sequence of whitespace by a single line break

or perhaps more readable and to the point, using str.replace:

l_new = [s.replace(' ', '\n') for s in l]
# this will replace all and only space characters
Sign up to request clarification or add additional context in comments.

2 Comments

Shorter? :P 33 chars in each
@HFBrowning Shorter in the sense of fewer function calls ;)
3

Try a list comprehension (this returns a new list with every element the same as in the old one, but with spaces replaced with linebreaks):

[element.replace(' ', '\n') for element in ls]

where ls is your list.

Alternatively, you could do a for-loop, using the replace method.

1 Comment

Ah schwobaseggl beat me to it.
0
l = ['Hello Yes', 'Good Now Order', 'Been There Before', 'Because']
list(map('\n'.join, map(str.split, l)))
# ['Hello\nYes', 'Good\nNow\nOrder', 'Been\nThere\nBefore', 'Because']

2 Comments

The quality of this answer will be greatly increased if you explain your code, especially for new users learning this.
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.