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

亡梦爱人 提交于 2019-12-17 10:59:20

问题


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()

回答1:


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.




回答2:


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()



回答3:


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.



来源:https://stackoverflow.com/questions/2121839/rstrip-not-removing-newline-char-what-am-i-doing-wrong

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!