How to split up a long list using \n

Posted by pypy on Stack Overflow See other posts from Stack Overflow or by pypy
Published on 2014-08-19T14:27:57Z Indexed on 2014/08/19 16:20 UTC
Read the original article Hit count: 232

Filed under:
|

Here is a long string that I convert to a list so I can manipulate it, and then join it back together. I am having some trouble being able to have an iterator go through the list and when the iterator reach, let us say every 5th object, it should insert a '\n' right there. Here is an example:

string = "Hello my name is Josh I like pizza and python I need this string to be really really long"

string = string.split()

# do the magic here

string = ' '.join(string)

print(string)

Output:

Hello my name is Josh
I like pizza and python
I need this string to
be really really long

Any idea how i can achieve this?

I tried using:

for words in string:
    if words % 5 == 0:
        string.append('\n')

but it doesn't work. What am I missing?

© Stack Overflow or respective owner

Related posts about python

Related posts about string