Remove \n from a string in Python (Backslash n)
Hello programmers, in this tutorial, we will learn how to remove \n from a string in Python (Backslash n).
We are going to do this using the
- replace() remove the part of a string or that particular character we pass as a parameter into this replace method and replace that part with the new characters we pass as a parameter.
- It takes two parameters as an input in which 1st is the character that we want to remove, and 2nd is the character that we want to replace at that position.
- we have to create a string that has ‘\n‘ throughout it.
- Then we use replace() method, which is an inbuilt method in Python.
- In this method, we pass two parameters,1st which we want to remove so that character in our string is ‘\n‘ .
- And 2nd which we want to replace at that place, so we just replace ‘\n‘ with empty string ‘ “” ‘.
- And we assign this to a new string, and at last, we see there is no ‘\n’ in our new string.
#string that contain '\n' string = "CodeSpeedy \n Coding \n Solution & Software \n Development" print("Old string: ",string) #using replace() function string = string.replace('\n',"") print("New string: ",string)
Old string: CodeSpeedy Coding Solution & Software Development New string: CodeSpeedy Coding Solution & Software Development
Hopefully, you have learned how to remove \n from a string in Python (Backslash n).