1

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?

pypy
  • 160
  • 1
  • 8
  • possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – Cory Kramer Aug 19 '14 at 14:30
  • @Cyber no this isn't a duplicate, what he wants in the link is something different – pypy Aug 19 '14 at 14:34
  • 1
    @pypy when you do `words.split()` you have a list... apply [this answer](http://stackoverflow.com/a/312644/1252759) from the linked question, join back each group with a space and add a `\n`... – Jon Clements Aug 19 '14 at 14:37
  • take a look at enumerate(), you can't mod on a string like you are, you need a number/index value – Levon Aug 19 '14 at 14:40
  • @Levon this is one of those rare cases where `enumerate` isn't *really* needed and looping over the indices is just fine :) – Jon Clements Aug 19 '14 at 14:45

8 Answers8

1

What you're doing wrong is attempting to change string in your example which doesn't affect the string contained in your list... instead you need to index into the list and directly change the element.

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

words = text.split()    
for wordno in range(len(words)):
    if wordno and wordno % 5 == 0:
        words[wordno] += '\n'

print ' '.join(words)

You don't want to call something string as it's a builtin module that is sometimes used and may confuse things, and I've also checked that wordno isn't 0 else you'll end up with a single word line in your rejoin...

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

In this case you should probably be creating a new string instead of trying to modify the existing one. You can just use a counter to determine which word you're on. Here's a very simple solution, though Jon Clements has a more sophisticated (and probably more efficient) one:

newstring = ""
str = "Hello my name is Josh I like pizza and python I need this string to be really really long"
strlist = str.split()

for i, words in enumerate(strlist):
  newstring += words
  if (i + 1) % 5 == 0:
    newstring += "\n"
  else:
    newstring += " "

`enumerate1 returns both the index of the word in your list of words, as well as the word itself. It's a handy automated counter to determine which word you're on.

Also, don't actually name your string string. That's the name of a module that you don't want to overwrite.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
0

I am sure this could be much shorter but this does what you want. They key improvements are a new string to hold everything and the use of enumerate to catch the ith word in the list.

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

for (i,word) in enumerate(string.split()):
    string2  = string2 + " " + word
    if (i + 1) % 5 == 0:        
        string2  = string2 + '\n'
print(string2)
BKay
  • 1,397
  • 1
  • 15
  • 26
0

you can use enumerate() on your string after you split it.

and iterate like that:

new_string_list = []

for index, word in string:
    if (index + 1) % 5 == 0:
        word += '\n'

    new_string_list.append(word)

string = ' '.join(new_string_list)
user3012759
  • 1,977
  • 19
  • 22
0

The problem with the for loop you attempted to use, is that it didn't keep the index of the word, and thus could not determine which word that was the 5th. By using enumerate(iterable) you can get the index of the word, and the word at the same time. You could also just use range(len(iterable)) to get the index and just do it the same way.

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


for word_num, word in enumerate(string):
    if word_num and word_num % 5 == 0:
        # access the array since changing only the variable word wont work
        string[word_num] += '\n'

string = ' '.join(string)

print(string)

Edit:

As @JonClements pointed out, this causes "Hello" to be printed on its own line, because 0%5 = 0. Therefore I added a check to see if word_num evaluates to True (which it does if it is not equal to 0)

naiad
  • 121
  • 6
0

Use enumerate to get index and % operation on i to append '\n' every n blocks

new_string_list = []
strlist = oldstr.split()

// do magic here 

for i,word in enumerate(strlist):
    new_string_list.append(word) #it is better
    #to append to list then join, using + to concatenate strings is ineffecient
    if count % 5 == 0:
        new_string_list.append('\n')

print("".join(new_string_list)) 
Sai Prasanna
  • 684
  • 1
  • 10
  • 25
0

Using list slicing...

s='hello my name is josh i like pizza and python i need this string to be really really long'

l=s.split()
l[4::5]=[v+'\n' for v in l[4::5] ]
print '\n'.join(' '.join(l).split('\n '))


hello my name is josh
i like pizza and python
i need this string to
be really really long
Matt Warren
  • 669
  • 8
  • 18
0

Horrible one-liner I cooked up as an example of what you should never do.

s='hello my name is josh i like pizza and python i need this string to be really really long'
print '\n'.join([' '.join(l) for l in [s.split()[i:i + 4] for i in range(0, len(s.split()), 4)]])
jambox
  • 584
  • 4
  • 15