首页 > 解决方案 > list pop() 没有正确打印出来

问题描述

我尝试制作一个文本编写程序,但文本删除部分似乎不起作用。它应该删除文本,但它只是用我的新输入替换文本。我是 python 新手,所以我会很感激一个简单的答案。这是我的代码:

import os
import msvcrt

lst = []
while True:
    userinput = msvcrt.getch()
    if userinput == "b'\\x08'":  # delete last input
        lst.pop()
        os.system('cls' if os.name == 'nt' else "printf '\033c'")
        print("".join(lst))
    elif userinput == "b'\\r'":  # enter key
        lst.append("\n")
    else:
        lst.append(userinput.decode("ASCII")) #normal text
        os.system('cls' if os.name == 'nt' else "printf '\033c'")
        print("".join(lst))

当我输入“Hello”时,它会打印:

>Hello

然后按退格键,我希望:

>Hell

但它只是停留

>Hello

然后当我按下一个按钮时,例如“f”然后它会打印出来:

>Hellf

标签: pythonpython-3.xlist

解决方案


您正在与字节的序列化表示进行比较。它永远不会匹配。

反而:

if userinput == b'\b':  # delete last input

和:

elif userinput == b'\r':  # enter key

\b与 相同\x08,但更具可读性


推荐阅读