Python for语句读取txt文件时不能识别其中字符

Python for语句读取txt文件时不能识别其中字符

问题描述:


global user_list
user_list = list()
f = open("borrowers.txt", 'r')
user_list = list(f)
print("Please input your name:")
borrower_name = input()
list1 = list()
for line in user_list:
    if line.startswith("#"):
        continue
    else:
        if line == borrower_name:
            #items_borrowed(borrower_name)
            print("ok!")
        else:
            print("Not a valid borrower to borrow item(s)")

输出结果如下
Please input your name:
Kelvin Yip #包含在borrower.txt中
Not a valid borrower to borrow item(s)
Not a valid borrower to borrow item(s)
Not a valid borrower to borrow item(s)

进程已结束,退出代码 0

borrower.txt内容如下:
#A list containing all the borrowers allowed to borrow items in this system
#Comments and empty lines are ignored

Kelvin Yip
Cow Leung


if line == borrower_name:

# 修改为
if line.strip() == borrower_name:

list(f) 的时候,每行末尾有一个 \n 换行