python print 换行 list_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()

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值