Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a string into substrings with a fixed number of tokens and add the strings to a list? python

I would like to split a string into smaller (equal) parts of the string and save the substrings to a list.

Example:

text = 'This is an example text. I would like to split this text. End'

Output with substring with 3 words:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

text_list = ['This is an', 'example text. I', 'would like to', 'split this text.', 'End']

>Solution :

I guess this is one way to solve it:

def returnPartionedText(text: str, x: int = 3) -> list:
    inputlist = text.split()
    return([" ".join(inputlist[i:i + x]) for i in range(0, len(inputlist), x)])

text = 'This is an example text. I would like to split this text. End'

print(returnPartionedText(text))

Result:

['This is an', 'example text. I', 'would like to', 'split this text.', 'End']

NOTE: This will only work on text with spaces as it splits on that.

Other than that it’s pretty simple, it slices the text into list of lists and joins them in the end.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading