代码之家  ›  专栏  ›  技术社区  ›  volting

rstrip未删除换行符我做错了什么[[副本]

  •  12
  • volting  · 技术社区  · 15 年前

    把我的头发拔出来。。。在过去的一个小时里我一直在玩这个,但我不能让它做我想做的,即删除新行序列。

    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()
    
    3 回复  |  直到 15 年前
        1
  •  34
  •   Community kfsone    7 年前

    线索在他的签名上 rstrip

    它返回字符串的一个副本,但删除了所需的字符,因此需要指定 line 新值:

    line = line.rstrip('\n')
    

    这允许有时非常方便的操作链接:

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

    作为 Max. S

    这就是它在许多框架和语言中的工作方式。如果您真的需要一个可变的字符串类型(通常出于性能原因),那么就有字符串缓冲区类。

        2
  •  3
  •   ghostdog74    15 年前

    你可以这样做

    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
  •  3
  •   GreenMatt    15 年前

    stripped_line = line.rstrip()
    

    然后写出一行。