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)
The output I am looking for is:
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
