Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string every n words into smaller Strings

Situation: I have a chunk of text that I want to break down into 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 to 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)

is not putting the list to my desired output together

like image 432
user273032 Avatar asked Oct 18 '25 21:10

user273032


1 Answers

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)]
like image 147
Hoopdady Avatar answered Oct 20 '25 09:10

Hoopdady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!