Python rstrip未删除换行符我做错了什么?
把我的头发拔出来。。。在过去的一个小时里我一直在玩这个,但我不能让它做我想做的,即删除新行序列Python rstrip未删除换行符我做错了什么?,python,newline,Python,Newline,把我的头发拔出来。。。在过去的一个小时里我一直在玩这个,但我不能让它做我想做的,即删除新行序列 def add_quotes( fpath ): ifile = open( fpath, 'r' ) ofile = open( 'ofile.txt', 'w' ) for line in ifile: if line == '\n': ofile.write( "\n\n" )
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()
线索在
rstrip
的签名中
它返回字符串的一个副本,但删除了所需的字符,因此您需要为line
指定新值:
line = line.rstrip('\n')
这允许有时非常方便的操作链接:
"a string".strip().upper()
正如注释中所说,Python字符串是不可变的,这意味着任何“变异”操作都将产生变异副本
这就是它在许多框架和语言中的工作方式。如果您确实需要一个可变字符串类型(通常是出于性能原因),那么就有字符串缓冲区类。您可以这样做
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()
正如Skurmedel的回答和评论中提到的,您需要做如下操作:
stripped_line = line.rstrip()
然后写出一行。更一般地说,Python中的字符串是不可变的。一旦创建,它们就无法更改。任何对字符串执行操作的函数都会返回一个副本。也许我应该把它写在答案中。谢谢,我知道它必须是简单的,…我自己的错,只是浏览了python文档。@max谢谢你提到这一点。