Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rstrip not removing newline char what am I doing wrong? [duplicate]

Tags:

python

newline

Pulling my hair out here... have been playing around with this for the last hour but I cannot get it to do what I want, ie. remove the newline sequence.

def add_quotes( fpath ):

        ifile = open( fpath, 'r' )
        ofile = open( 'ofile.txt', 'w' )

        for line in ifile:
            if line == '\n': 
                ofile.write( "\n\n" )
            elif len( line ) > 1:
                line.rstrip('\n')
                convertedline = "\"" + line + "\", "
                ofile.write( convertedline )

        ifile.close()
        ofile.close()
like image 323
volting Avatar asked Jan 23 '10 02:01

volting


People also ask

Does Rstrip remove newline?

rstrip('\n') . This will strip all newlines from the end of the string, not just one.

What does Rstrip \n Do?

The rstrip() method returns a copy of a string with the trailing characters removed.

How do you ignore a newline in Python?

Using strip() method to remove the newline character from a string. The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.


3 Answers

The clue is in the signature of rstrip.

It returns a copy of the string, but with the desired characters stripped, thus you'll need to assign line the new value:

line = line.rstrip('\n')

This allows for the sometimes very handy chaining of operations:

"a string".strip().upper()

As Max. S says in the comments, Python strings are immutable which means that any "mutating" operation will yield a mutated copy.

This is how it works in many frameworks and languages. If you really need to have a mutable string type (usually for performance reasons) there are string buffer classes.

like image 190
Skurmedel Avatar answered Sep 30 '22 15:09

Skurmedel


you can do it like this

def add_quotes( fpath ):
        ifile = open( fpath, 'r' )
        ofile = open( 'ofile.txt', 'w' )
        for line in ifile:
            line=line.rstrip()
            convertedline = '"' + line + '", '
            ofile.write( convertedline + "\n" )
        ifile.close()
        ofile.close()
like image 40
ghostdog74 Avatar answered Sep 30 '22 15:09

ghostdog74


As alluded to in Skurmedel's answer and the comments, you need to do something like:

stripped_line = line.rstrip()

and then write out stripped_line.

like image 32
GreenMatt Avatar answered Sep 30 '22 14:09

GreenMatt