Predictive Hacks

How to remove new line feeds `\n` from strings in Python

The new line feeds can be of the form \n or \r or both. We can remove them from a string using the strip() method.

'this is a string\n'.strip()

And we get:

'this is a string'

Note that there is also the lstrip() and rstrip() for left and right stripping of the whitespaces in text. We can also be more specific by typing:

'this is a string\n'.strip("\n")

Or you can use the replace function. Assume that the input_text has new line feeds in the middle of the string. We can clean them as follows:

input_txt = input_txt.replace('\n',' ')

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s