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

Time:11-27

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:

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.

CodePudding user response:

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
  • Related