Python打印不需要的多余换行符 [英] Python prints unwanted extra newline

查看:208
本文介绍了Python打印不需要的多余换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is that Python always prints an extra newline when I run the code below? I tried to re-write the code to eliminate any unintended blank space but it still prints out an extra new line. Anyone knows why? Thanks.

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

推荐答案

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

The reason that your code prints an extra newline is because in the last iteration of the names_in function, the variable names is ``, which gets appended to the end of names_list, causing the print_names function to run print '' at the end, which prints an extra newline.

这篇关于Python打印不需要的多余换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆