python - 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
解决方案
您正在与字节的序列化表示进行比较。它永远不会匹配。
反而:
if userinput == b'\b': # delete last input
和:
elif userinput == b'\r': # enter key
\b
与 相同\x08
,但更具可读性
推荐阅读
- flask - Flask:确保删除临时上传文件的最佳方法
- python - 为什么python库“python-pptx”没有得到所有的选择数据?
- sql - 按日期列的子集对增量表进行分区
- networking - 如何路由来自特定 NIC 卡的计算机流量
- r - 选择数据框中包含特定值的行
- java - 对 CSV 特殊字符使用临时占位符是一种不好的做法吗?
- mysql - 如何通过客户 ID 识别客户订单
- java - Java Builder Pattern 实现,哪个更好?
- angularjs - 如何使具有异步函数的for循环AngularJs作为阻塞函数(同步)运行?
- hsm - TriCore HSM 通用通信