![](/img/trans.png)
[英]How to remove this extra trailing space at the end of each line in python3
[英]How to remove extra space from end of the line before newline in python?
我是python的新手。 我有一个程序,该程序读取具有不同字符的输入文件,然后将该文件中的所有唯一字符写入输出文件,并且每个文件之间都有一个空格。 问题在于最后一个字符之后有一个多余的空间(在换行符之前)。 如何删除?
我的代码:
import sys
inputName = sys.argv[1]
outputName = sys.argv[2]
infile = open(inputName,"r",encoding="utf-8")
outfile = open(outputName,"w",encoding="utf-8")
result = []
for line in infile:
for c in line:
if c not in result:
result.append(c)
outfile.write(c.strip())
if(c == ' '):
pass
else:
outfile.write(' ')
outfile.write('\n')
使用outfile.write(' ')
,您可以在每个字符后写一个空格(除非该字符是一个空格)。 因此,您必须避免写最后一个空格。 现在,在完成阅读之前,您无法确定是否有任何给定的字符是最后一个字符,因此,这不像您可以放入if
语句来测试该字符,但是有几种解决方法:
c
之前而不是在字符c
之前写空格。 这样,你有空间跳过是第一个字符前一个,那你绝对可以识别if
语句和布尔变量。 如果这样做,请确保如果第一个或第二个c
本身是空格,请检查是否获得正确的结果。 或者,您可以避免在最后写任何东西。 只需保存您看到的所有字符-您已经在列表result
进行了此操作-一次性全部写入。 您可以使用
' '.join(strings)
将字符串列表(在本例中为您的字符)之间用空格连接在一起,这将自动省略尾随空格。
为什么最后添加if块呢? 您的程序在末尾添加了额外的空间。
import sys
inputName = sys.argv[1]
outputName = sys.argv[2]
infile = open(inputName,"r",encoding="utf-8")
outfile = open(outputName,"w",encoding="utf-8")
result = []
for line in infile:
charno = 0
for c in line:
if c not in result:
result.append(c)
outfile.write(c.strip())
charno += 1
if (c == ' '):
pass
elif charno => len(line):
pass
else:
outfile.write(' ')
outfile.write('\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.