菠萝菠萝哒12 2021-11-15 12:27 采纳率: 100%
浏览 26
已结题

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

  • 写回答

1条回答 默认 最新

  • CSDN专家-文盲老顾 2021-11-15 12:35
    关注
    
    if line == borrower_name:
    
    # 修改为
    if line.strip() == borrower_name:
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 11月16日
  • 已采纳回答 11月15日
  • 创建了问题 11月15日