【问题标题】:Python Jupyter notebook throws unicode error in one instance but not anotherPython Jupyter notebook 在一个实例中抛出 unicode 错误,但在另一个实例中没有
【发布时间】:2020-08-27 15:20:39
【问题描述】:

我知道如何解决这个问题(r、双 \ 等等。)但它确实让我很头疼,我不明白为什么下面的代码:

basepath = "C:\Users\Rio\Pictures\Screenshot"

引发错误:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

虽然下面的代码(看起来和我一模一样)工作得很好:

basepath = "D:\Teaching content\Poker\Zenith Poker 2020"

【问题讨论】:

    标签: python-3.x string operating-system


    【解决方案1】:

    当 Python 看到 "\ 时,它会尝试进行 unicode 转义,这是错误的根源。这取决于"\" 后面的字符。在 Windows 上,文件路径通常包含"\U",这会抛出 Python。当您处理包含大量 "\" 字符的字符串时,请改用原始字符串。

    basepath = r"C:\Users\Rio\Pictures\Screenshot"
    

    或者只是用双斜杠重写你的字符串

    basepath = "C:\\Users\\Rio\\Pictures\\Screenshot"
    

    当 Python 看到 "\\" 时,它会将其理解为 "\"

    【讨论】:

      【解决方案2】:

      我认为你应该试一试 PATH 模块:

      使用这个:

          from pathlib import Path
          basepath = Path('put your path here ') # using either r string or '\\'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-31
        • 2016-06-24
        • 2020-02-06
        相关资源
        最近更新 更多