rstrip无法删除换行符char我在做什么错? [英] rstrip not removing newline char what am I doing wrong?
问题描述
在这里拉头发...最近一个小时一直在玩这个游戏,但是我不能让它做我想做的事,即.删除换行序列.
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()
推荐答案
线索在rstrip
的签名中.
它返回字符串的副本,但是去除了所需的字符,因此您需要为line
分配新值:
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()
为最大值. S 在评论中说,Python字符串是不可变的,这意味着任何变异"操作都将产生变异的副本.
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.
这篇关于rstrip无法删除换行符char我在做什么错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!