【问题标题】:Error (unicode error) 'utf-8' codec can't decode byte - code = compile(f.read(), fname, 'exec')错误(unicode 错误)'utf-8' 编解码器无法解码字节 - code = compile(f.read(), fname, 'exec')
【发布时间】:2022-07-26 23:08:19
【问题描述】:

我是 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。我已经尝试过 # -- coding: utf-8 -- 但它不起作用

【问题讨论】:

  • 我可以毫无问题地运行您的代码。你是用 VS 输入的,还是复制粘贴的?
  • 我用VS输入。这真的很奇怪。我的视觉工作室可能有问题吗?我该如何解决?

标签: python visual-studio unicode syntax-error python-unicode


【解决方案1】:

从表面上看,编译器在使用“ñ”时遇到了问题,因为它可能会遇到这个问题,并且它位于位置 4,即错误消息突出显示的位置。请参阅此答案以获得类似的解决方案:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 2: invalid continuation byte

您的编码似乎混淆了。 \xf1 - 错误中出现的字节编码 - 对应于带有 latin1 编码的“ñ”:

>>>"España".encode("latin1")
b'Espa\xf1a'
>>>b'\xf1'.decode('latin1')
'ñ'

utf-8 希望将 ñ 编码为 '~' 和 'n' 的组合:

>>>b'\xc3\xb1a'.decode('utf-8')
'ñ'

实际上,由于您的计算机将 ñ 识别为 latin1 编码,因此您需要使用它而不是 utf-8。因此,请尝试将您的编码类型更改为 latin1。这有帮助吗?

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 2021-03-12
    • 1970-01-01
    • 2016-11-03
    • 2020-07-17
    • 2019-11-10
    • 1970-01-01
    • 2021-12-18
    • 2015-08-24
    相关资源
    最近更新 更多