【问题标题】:Python prints unwanted extra newlinePython 打印不需要的额外换行符
【发布时间】:2015-11-14 02:03:19
【问题描述】:

为什么当我运行下面的代码时,Python 总是打印一个额外的换行符?我试图重新编写代码以消除任何意外的空白,但它仍然打印出一个额外的新行。有谁知道为什么?谢谢。

def main():
    names_in()                          #This function import the file and read all the content and put the content into a list. 

    print_names(names_in)        # Before the names are sorted.

def names_in():
    infile = open('names.txt','r')
    names_list = []                 #empty list.
    names = infile.readline()   # read contents.

    #loop for continue to read.
    while names != '':
        names = infile.readline()       #continue to the next name.
        names = names.rstrip('\n')    #return a copy of the string which all \n has been stripped from the end of the string.
        names_list.append(names)    #write names in the file into a list.
    infile.close()

    return names_list                     #return the list back to the function.



def print_names(names_in):        #This function will print out the names in the list one per line, single-spaced.
    for item in names_in():
        print(item)


main()

这在我的输入文件中:

Riggs, Jerry
Stone, Ruby
Wood, Holly
Dover, Ilene
Funt, Ella
Storm, Wayne
Lowe, Lyle
Free, Bjorn
Caine, Candy
Carr, Rex
Downs, Mark
Twain, Lionel
Thorn, Rose
Shore, Rocky
Bush, Rose
Waters, Muddy
Graves, Doug
Stone, Roxanne
Rivers, Wade

【问题讨论】:

  • 你读了两次输入文件;如果print_names() 再次调用它,您不需要先调用names_in() 并丢弃结果。

标签: python input newline


【解决方案1】:

您的代码打印额外换行符的原因是因为在 names_in 函数的最后一次迭代中,变量 names 是 ``,它被附加到 names_list 的末尾,导致 print_names最后运行print '' 的函数,它会打印一个额外的换行符。

【讨论】:

  • 感谢您的解释。无论如何我可以解决这个问题吗?我不知道如何修改循环,以便它可以读取文件中的每一行而不是同时打印额外的换行符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多