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

Newline in Python after any number of white spaces

I want to split a string in Python with newline after specific number of white spaces. The closest result I found was to split by character

original_text = "Hi! Today is a great day. There is good sunshine and birds are chirping"
re.sub("(.{8})", "\\1\n", original_text, 0, re.DOTALL)

enter image description here

The output I am looking for is:

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

Hi! Today is a great
day. There is good sunshine
and birds are chirping

How can we do this with/without regex?

>Solution :

Suggestion without using regex (assuming the text will always be normally split using spaces):

# x indicates how many spaces you want to split on
def returnNewlineText(inputlist: list, x: int = 5) -> list:
    return("\n".join([" ".join(inputlist[i:i + x]) for i in range(0, len(inputlist), x)]))

original_text = "Hi! Today is a great day. There is good sunshine and birds are chirping"
print(returnNewlineText(original_text.split()))

Result:

Hi! Today is a great
day. There is good sunshine
and birds are chirping
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