Python待办事项程序报错:列表字符串拼接类型错误及换行符去除需求
待办事项程序的TypeError问题及修复方案
问题点
- 运行代码时触发
TypeError,错误行是print("here is you existing todo", todos + '\n'),报错信息:can only concatenate list (not "str") to list(无法将列表与字符串拼接) - 需要移除列表元素末尾的
\n(例如将human\n转换为human)
错误回溯:
Traceback (most recent call last): File "C:\Users\awani\PycharmProjects\pythonProject\main.py", line 28, in <module> print("here is you existing todo", todos + '\n') ~~~~~~^~~~~~ TypeError: can only concatenate list (not "str") to list
修复步骤
1. 解决TypeError错误
todos是file.readlines()返回的列表类型,不能直接和字符串'\n'做拼接操作。要正确打印现有待办项,需要先把列表元素处理成可读的字符串:
- 遍历列表,用
strip()去掉每个元素的换行符 - 用
'\n'把处理后的元素连接成一个完整字符串 - 再打印输出
把错误行替换为:
formatted_todos = '\n'.join([item.strip() for item in todos]) print("here is your existing todo:\n", formatted_todos)
(顺便修正了原文的拼写错误:you → your)
2. 统一处理元素的换行符
建议在读取文件时就统一去掉所有元素的换行符,后续写入文件时再添加,避免重复处理:
把所有读取文件的代码:
todos = file.readlines()
替换为:
todos = [item.strip() for item in file.readlines()]
这样后续添加新待办项时,只需要在输入内容后拼接'\n'再写入文件即可。
修改后的完整代码
while True: user_action = input("Type add,show,exit,edit,complete: ") user_action = user_action.strip() if 'add' in user_action: todo_content = user_action[4:].title() with open('todos.txt', 'r') as file: todos = [item.strip() for item in file.readlines()] todos.append(todo_content) with open('todos.txt', 'w') as file: # 写入时统一添加换行符 file.writelines([item + '\n' for item in todos]) elif 'show' in user_action: with open('todos.txt', 'r') as file: todos = [item.strip() for item in file.readlines()] for index, item in enumerate(todos): row = f"{index + 1}-{item}" print(row) elif 'edit' in user_action: user_input = int(user_action[5:]) user_value = user_input - 1 with open('todos.txt', 'r') as file: todos = [item.strip() for item in file.readlines()] # 修复打印逻辑 formatted_todos = '\n'.join(todos) print("here is your existing todo:\n", formatted_todos) todos[user_value] = input("Enter a new todo:").title() with open('todos.txt', 'w') as file: file.writelines([item + '\n' for item in todos]) elif 'complete' in user_action: user_input = int(input("Enter a number to complete todo: ")) with open('todos.txt', 'r') as file: todos = [item.strip() for item in file.readlines()] index = user_input - 1 todo_to_remove = todos[index] todos.pop(index) with open('todos.txt', 'w') as file: file.writelines([item + '\n' for item in todos]) message = f"This todo will be removed:{todo_to_remove}" print(message) elif 'exit' in user_action: print("Bye!") break else: print("Check and type again ") print("Bye !")
内容的提问来源于stack exchange,提问作者Devil Is Dead
相关产品推荐
相关产品推荐

