How do I transform 10 line breaks in 1 in Python?

Question:

Example:

I have this text

Example 123









Example 456

and I have to transform into this:

Example 123
Example 456

Obs: 10 line breaks it’s just a example, can be any number (3,4,6…)

Asked By: Emily

||

Answers:

Since you have tagged this question with the regex tag, you can do

import re
text="""Example 123









Example 456
"""
print(re.sub(r"n{2,}", "n", text))

which replaces all consecutive line breaks with one line break.

Answered By: Mia
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.