我的代码如下:
import msvcrt
userKeyPress = [""]
x = 0
whereInList = 0
def writeToList(char):
if " " not in char:
userKeyPress[whereInList] = userKeyPress[whereInList] + char
while x == 0:
userChar = msvcrt.getch()
userChar = userChar.decode("ASCII")
if " " in userChar:
whereInList = whereInList + 1
userKeyPress.extend(" ")
elif " " not in userChar and "q" not in userChar:
writeToList(userChar)
elif "q" in userChar:
print(userKeyPress)
x = 1
它接受用户输入并将其放入列表中,其中空格创建新的列表值。运行时,它能够转换用户按字节字符串格式输入的第一个字母,但所有其他字符不是第一个字母。
例如,如果我在键盘上键入字母“a”,然后键入“b”,则返回“c”
['a\x00b\x00c\x00']
第一个字母很好,但是之后的两个字母都是\ x00。为什么会这样,我该怎么做才能解决它?
看起来您正在将UTF-16编码字符转换为ASCII。 UTF-16是Windows中的默认编码,表示两个字节中的所有字符,这意味着ascii集中的所有字符都将包含空字节\x00
。
阅读文档,我希望msvcrt.getch()
返回ASCII编码字符,所以这是意料之外的。
无论如何,如果用decode("ASCII")
替换decode('utf16')
,你应该得到预期的输出。