0
为什么当我运行下面的代码时,Python总是打印额外的换行符?我试图重新编写代码以消除任何意外的空白,但它仍然会打印出一个额外的新行。有人知道为什么谢谢。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()'并放弃结果。 –