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

Question:

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.

Asked By: lediwa

||

Answers:

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

  • The regex pattern looks like r"(sns)"

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"(sns)"
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
Answered By: ScottC
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.