键入错误:尝试删除 ' ' 从创建的列表中

问题描述 投票:0回答:1

我正在尝试删除 ' ' 从我创建的列表中,例如:查找 找到 但它在列表中。 我是 python 新手,想通过在线课程学习,我想为 TODO 列表创建一个程序 我也遇到过这个错误。

while True:
    user_action = input("Type add,show,exit,edit,complete: ")
    user_action = user_action.strip()

    if 'add' in user_action:
        todo = user_action[4:].title() + "\n"
        with open('todos.txt', 'r') as file:
            todos = file.readlines()

        todos.append(todo)
        with open('todos.txt', 'w') as file:
            file.writelines(todos)

    elif 'show' in user_action:
        with open('todos.txt', 'r') as file:
            todos = file.readlines()

        for index, item in enumerate(todos):
            new_item = item.strip()
            row = f"{index + 1}-{new_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 = file.readlines()
            print("here is you existing todo", todos + '\n')

        todos[user_value] = input("Enter a new todo:").title() + '\n'
        with open('todos.txt', 'w') as file:
            file.writelines(todos)
    elif 'complete' in user_action:
        user_input = int(input("Enter a number to complete todo: "))
        with open('todos.txt', 'r') as file:
            todos = file.readlines()
        index = user_input - 1
        todo_to_remove = todos[index].strip()

        with open('todos.txt', 'w') as file:
            file.writelines(todos)
            todos.pop(index)
        with open('todos.txt', 'w') as file:
            file.writelines(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 !")

该代码产生以下错误:

**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**

我正在尝试删除 ' ' 从我创建的列表中。 例如:人类 到 人类

python list concatenation typeerror srt
1个回答
0
投票

与 file.readlines() 的输出类似,

todos
是一个字符串列表,其中
todos[:-1]
的字符串以
"\n"
结尾。

嗯,有很多方法可以解决您的问题。例如,我们可以编写这样的列表理解:

tasks = [task.strip() for task in todos]

我认为这是我们在这种情况下可以做的最Pythonic 的代码。 你的代码变成:

with open('todos.txt', 'r') as file:
    todos = file.readlines()
    tasks = [task.strip() for task in todos]
    print("here is you existing todo", *tasks)

为了解释一下,

*tasks
拿起
tasks
并像
tasks[0], tasks[1], ..., tasks[n]
一样打开它。

其实

print("here is you existing todo", *tasks)

一模一样
print("here is you existing todo", tasks[0], tasks[1], ..., tasks[n])

并且分隔符(默认情况下是一个空格)位于输出中的所有参数之间。

我希望我回答了你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.