问题描述
我尝试制作文本编写程序,但文本删除部分似乎不起作用。它应该删除文本,但它只是用我的新输入替换文本。我是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
然后按 Backspace,我希望:
>Hell
但它只是停留
>Hello
然后当我按下按钮时,例如"f" 然后它打印出来:
>Hellf
解决方法
您正在与字节的序列化表示进行比较。它永远不会匹配。
相反:
if userinput == b'\b': # delete last input
和:
elif userinput == b'\r': # enter key
\b
与 \x08
相同,但更具可读性