2017-06-02 171 views
0

此作业的一部分是从另一个程序写入的.txt中去除任何空格。我想我已经下来正确,但是从这段代码输出出来为:Python:从文件输出中删除空格(剥离空白)

克里斯

约翰

我想删除空格这些之间。我在格式部分丢失了什么?

def main(): 
file = open("golf.txt", 'r') 
line = file.readline() 
while line != '': 
    print(format(line)) 
    line = file.readline() 
file.close() 
main() 

回答

0

您正在阅读的每行都包含一个换行符(\n),标记行的结尾。您需要在打印之前将其删除。例如:

print(format(line.rstrip())) 

rstrip将默认删除所有空白而不传入参数。

+0

完美,谢谢!你能否也将我链接到一个格式化功能的文档?我似乎无法找到它,我是新来的编码,我发现python文件是一种压倒性的导航。但也许我应该更加努力。感谢帮助,朋友! :) – Bbtopher

+0

在这种情况下,您应该不需要使用格式,因为rstrip正在为您完成工作。这里有一些帮助你入门的链接。 https://docs.python.org/3.6/library/functions.html#format https://docs.python.org/3.6/library/string.html#formatspec – digd

0
def main(): 
    file = open("golf.txt", 'r') 
    lines = file.readlines() 
    for line in lines: 
     line = line.strip() 
     if line=='' or line=="/n": 
      pass 
     else: 
      print(line) 
    file.close() 
main()