close

How to remove \n and \r from a string

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to remove \n and \r from a string in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to remove \n and \r from a string?

  1. How to remove \n and \r from a string?

    However, if you only want to get rid of \r and they might not be at the end-of-line, then str.replace() is your friend:

  2. remove \n and \r from a string

    However, if you only want to get rid of \r and they might not be at the end-of-line, then str.replace() is your friend:

Method 1

A simple solution is to strip trailing whitespace:

with open('gash.txt', 'r') as var:
    for line in var:
        line = line.rstrip()
        print(line)

The advantage of rstrip() over using a [:-2] slice is that this is safe for UNIX style files as well.

However, if you only want to get rid of \r and they might not be at the end-of-line, then str.replace() is your friend:

line = line.replace('\r', '')

If you have a byte object (that’s the leading b') the you can convert it to a native Python 3 string using:

line = line.decode()

Method 2

to remove carriage return:

  • line = line.replace('\r', '')

to remove tab

  • line = line.replace('\t', '')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read