语法unicode错误pygame



在我正在做的一个项目中,我必须加载几十张图片。但是,如果我尝试加载它们中的任何一个,像这样:

twoc = pygame.image.load("C:UsersZ & Z AzamAppDataLocalProgramsPythonPython35ScriptsCards2_of_clubs.png")

我得到这个消息:

    "C:UsersZ & Z AzamAppDataLocalProgramsPythonPython35python.exe" "C:/Users/Z & Z Azam/Desktop/New folder (2)/Python Stuff/PycharmProjects/ProjectGambler/Graphics-Cards.py"
  File "C:/Users/Z & Z Azam/Desktop/New folder (2)/Python Stuff/PycharmProjects/ProjectGambler/Graphics-Cards.py", line 16
    twoc = pygame.image.load("C:UsersZ & Z AzamAppDataLocalProgramsPythonPython35ScriptsCards2_of_clubs.png")  # Lines 15-66 bring all the cards into the program
                            ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
我不知道我做错了什么。有人能帮我吗?

更新:所以我已经用/替换了文件地址中的每个。同样,直到:

    "C:UsersZ & Z AzamAppDataLocalProgramsPythonPython35python.exe" "C:/Users/Z & Z Azam/Desktop/New folder (2)/Python Stuff/PycharmProjects/ProjectGambler/Graphics-Cards.py"
Traceback (most recent call last):
  File "C:/Users/Z & Z Azam/Desktop/New folder (2)/Python Stuff/PycharmProjects/ProjectGambler/Graphics-Cards.py", line 28, in <module>
    fivc = pygame.image.load("C:/Users/Z & Z Azam/AppData/Local/Programs/Python/Python35/Scripts/Cards/5_of_clubs")
pygame.error: Couldn't open C:/Users/Z & Z Azam/AppData/Local/Programs/Python/Python35/Scripts/Cards/5_of_clubs
Process finished with exit code 1

暴露错误的最小示例:

s = "U"

在Python中,反斜杠用作转义序列,Uxxxx模式用于声明unicode字符,同时保持源代码仅为ascii。通过在字符串中使用Users, U之后的字符串是无效的十六进制数,因此引发异常。

最快修复-标记字符串为raw:

s = r"C:UsersZ & Z AzamAppDataLocalProgramsPythonPython35ScriptsCards2_of_clubs.png

基本上你需要在你的字符串中添加一个转义斜杠。所以你将以两个斜杠结束,像这样:

twoc = pygame.image.load("C:\Users\Z & Z Azam\AppData\Local\Programs\Python\Python35\Scripts\Cards\2_of_clubs.png")

或者另一种方法,将你的反斜杠改为正斜杠:

  twoc = pygame.image.load("C:/Users/Z & Z Azam/AppData/Local/Programs/Python/Python35/Scripts/Cards/2_of_clubs.png")

相关内容

最新更新