我是Python新手。我正在尝试运行此代码:
llaves=("España","Francia","Inglaterra")
dicPaises={llaves[0]:"Madrid",llaves[1]:"Paris",llaves[2]:"Londres"}
print(dicPaises)
结果是以下错误:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 444, in main
run()
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 285, in run_file
The thread 0x1 has exited with code 0 (0x0).
runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\runpy.py", line 267, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\runpy.py", line 242, in _get_code_from_file
code = compile(f.read(), fname, 'exec')
File "C:\Users\JANSIR\source\repos\Pruebas\Pruebas.py", line 8
llaves=("España","Francia","Inglaterra")
^
SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xf1 in position 4: invalid continuation byte
The program 'python.exe' has exited with code 1 (0x1).
我正在使用 Visual Studio 和 Python 3.9。我已经尝试过#--编码:utf-8--但它不起作用
从表面上看,编译器对“ñ”有问题,因为它可能会遇到困难,并且它位于位置 4,这是错误消息突出显示的位置。请参阅此答案以获取类似的解决方案:
UnicodeDecodeError:“utf-8”编解码器无法解码位置 2 中的字节 0xf1:无效的连续字节
您的编码似乎混淆了。 \xf1 - 错误中引发的字节编码 - 对应于 latin1 编码的 'ñ':
>>>"España".encode("latin1")
b'Espa\xf1a'
>>>b'\xf1'.decode('latin1')
'ñ'
而 utf-8 希望将 ñ 编码为“~”和“n”的组合:
>>>b'\xc3\xb1a'.decode('utf-8')
'ñ'
正如 @JosefZ 指出的,您应该始终使用 utf-8 编码,并告诉 VS Code 使用此编码而不是 latin1。我想你可以在这里找到你需要的选项:
如果您按 ctrl+f 进行“配置 VS Code”,您应该会找到您需要的信息。
您的问题是,使用 Python 和 UTF-8 的 Visual Studio 2022 中存在 bug。
我的解决方案是: