Python: How to split text on 2 or more new lines without importing modules.
Example shows how to use while loop to split text on 2 or more new lines without extra modules.
Input:
"Hello World.\nI'm very happy today.\n\n\n\n\nHow are you?\n\n\nBye."
Output:
["Hello World.nI'm very happy today.", "How are you?", "Bye."]
Code loops char by char and counts new lines \n. When there is other char then if count is 2 or more then it moves previous text without new lines, get rest of text, and reset variables. When there is other char but count` is zero or one then it move to next char.
text = "Hello World.\nI'm very happy today.\n\n\n\n\nHow are you?\n\n\nBye."
results = [] # list for splited text
count = 0 # count new lines
i = 0 # index to move in text to next char
while text and i < len(text):
if text[i] == '\n':
count += 1 # count new line
i += 1 # move to next char
else:
if count > 1:
results.append(text[:i-count])
inp = text[i:]
count = 0
i = 0
else:
count = 0 # reset counter
i += 1 # move to next char
if inp:
results.append(text) # add rest
print(results)
If you like it
Buy a Coffee
Buy a Coffee