user273032 user273032 - 1 year ago 79
Python Question

Python: Split String every n word in smaller Strings

Situation: I have a chunk of text that i want to break down in smaller strings. After every n Words.

text = This is a small example Text, showcasing my desired output.

Should be split with n = 4 into:

textList = ['This is a small', 'example Text, showcasing my', 'desired output.']

My idea is split it in a list with only single words using:

n = len(text)

textList = text.split(' ', n)

And then use join() to put it together but i'm stuck because:

for x in range(0, 3):
' '.join(textList)

isnt putting the list to my desired output together

Answer Source

Try this:

text = 'This is a small example Text, showcasing my desired output.'
text = text.split()
n = 4
[' '.join(text[i:i+n]) for i in range(0,len(text),n)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download