This question already has answers here:
rstrip not removing newline char what am I doing wrong? [duplicate]
                                
                                    (3个答案)
                                
                        
                                5年前关闭。
            
                    
试图弄清楚为什么这些意外的换行符是用简单的脚本打印的。我在脚本中要做的所有事情都被读取到一个文件中,并打印出每一行的内容。

代码是这样的:

#!/usr/bin/python
import sys

# This script should just iterate over a file and echo the contents of each line

f=open(sys.argv[1],'r')
for line in f:
  line.rstrip('\n')
  print "Line 1 is: " + line
f.close()


输入文件只有两行:

#cat users
root
dontexist
#


当我使用此输入文件运行脚本时,输出中会有额外的换行符:

#./test.py users
Line 1 is: root

Line 1 is: dontexist

#


我想念什么?谢谢大家

最佳答案

rstrip和类似的功能(例如,replace,strip等)返回具有更改后的字符串的副本,而不是在原地更改该字符串。您想做line = line.rstrip("\n")

09-07 10:59