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

Python3: Remove \n from middle of the string while keeping the one in the end

I am new to Python and stuck with this problem. I have a multiline string:


My name is ABCD \n I am 20 years old \n I like to travel
his name is XYZ \n he is 20 years old \n he likes to eat
your name is ABC \n you are 20 years old \n you like to play

I want to replace all \n with space but keep the sentence as it is.

The desired output 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

My name is ABCD I am 20 years old I like to travel
his name is XYZ he is 20 years old he likes to eat
your name is ABC you are 20 years old you like to play

I tried: str.replace('\n', ' ') but it gives:

My name is ABCD I am 20 years old I like to travel his name is XYZ he is 20 years old he likes to eat your name is ABC you are 20 years old you like to play

Which is not what I want. Can you please guide me? Thank you in advance.

>Solution :

You can use regex to find the newlines (\n) that are surrounded by a space \s.

  • The regex pattern looks like r"(\s\n\s)"

Here is the example code:

import re

test_string = """
My name is ABCD \n I am 20 years old \n I like to travel
his name is XYZ \n he is 20 years old \n he likes to eat
your name is ABC \n you are 20 years old \n you like to play
"""

pattern = r"(\s\n\s)"
new_text = re.sub(pattern, "", test_string)

print(new_text)

OUTPUT:

My name is ABCD I am 20 years old I like to travel
his name is XYZ he is 20 years old he likes to eat
your name is ABC you are 20 years old you like to play
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