Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么只有一个字符被正确更改?_Python_Windows_Python 3.x - Fatal编程技术网

Python 为什么只有一个字符被正确更改?

Python 为什么只有一个字符被正确更改?,python,windows,python-3.x,Python,Windows,Python 3.x,我的代码如下: 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.

我的代码如下:

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')
,则应获得预期的输出。

事实上,所有三个字母后面都有一个空终止符(
\x00
)。如果你想的话,你可以把它切掉。这很有道理,非常感谢!如果你想给我一个完整的答案,我会把它标记为你的答案。(作为非评论)@ForceBru:这是
msvcrt.getch()
的副作用吗?我不明白为什么这里会有一个空终止符,但我不太使用Windows。文档说
getch
应该处理ascii字符。您可以尝试改用
msvcrt.getwch()
。这应该返回一个unicode字符,解码步骤可能不需要。@usr2564301,我不是很确定,但我认为它只是返回以NULL结尾的C字符串。这可能是不正确的,因为如果我要开发这个函数,我只会返回原始整数(由
ord
返回)或单个字符,所以返回C字符串对我来说没有多大意义。是的,出乎意料。文档读起来像是应该使用线程当前的“ANSI代码页”。是否可以通过键入(或管道)测试字符(如欧元)进行测试,并且Windows仍然使用ANSI代码页?我手头没有一台Windows计算机来测试这个,但是如果有人可以尝试一下,请随意编辑我的答案以添加更多信息。文档还建议使用
msvcrt.getwch()
,它应该将字符作为正确解码的unicode字符串返回。