把我的头发拉到这里......在最后一小时里一直在玩这个但是我不能让它做我想做的事,即.删除换行序列.
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()
Run Code Online (Sandbox Code Playgroud)
Sku*_*del 22
线索是签名rstrip.
它返回字符串的副本,但删除了所需的字符,因此您需要分配line新值:
line = line.rstrip('\n')
Run Code Online (Sandbox Code Playgroud)
这允许有时非常方便的操作链接:
"a string".strip().upper()
Run Code Online (Sandbox Code Playgroud)
作为马克斯.S在评论中说,Python字符串是不可变的,这意味着任何"变异"操作都会产生变异副本.
这就是它在许多框架和语言中的工作方式.如果你真的需要一个可变的字符串类型(通常是出于性能原因),那么就有字符串缓冲类.