简体   繁体   中英

Python prints unwanted extra newline

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()

This in my input file:

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附加在names_list的末尾,导致print_names函数在末尾运行print '' ,这打印额外的换行符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM