简体   繁体   中英

Python Notepad++ encoding error

I am using Python for the first time and am running into an encoding error that I can't seem to get around. Here is the code:

   #!/usr/bin/python
   #-*- coding: utf -*-
   import pandas as pd
   a = "C:\Users"
   print(a) 

When I do this, I get:

File "C:\\Users\\Public\\Documents\\Python Scripts\\ImportExcel.py", line 5 a = "C:\\Users" ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in positio n 2-3: truncated \\UXXXXXXXX escape

In Notepad++ I have tried all of the encoding options. Nothing seems to work. Any suggestions?

Specifically, the problem is that the '\\' is an escape character. If you want to print the string "C:\\Users" then you have to do it thus:

a = "C:\\Users"

Hope this helps.

The error message suggests you're on a Windows machine, but you're using *nix notation for #!/usr/bin/python . That line should look something like #!C:\\Python33\\python.exe on a Windows machine, depending on where you've installed Python.

使用此代码: # -*- coding: utf-8 -*-代替#-- coding: utf --

You can set the encoding in Notepad++, but you also need to tell Python about it.

In legacy Python (2.7), source code is ASCII unless specified otherwise. In Python 3, source code is UTF-8 unless otherwise specified.

You should use the following as the first or second line of the file to specify the encoding of the source code. The documentation gives:

# -*- coding: <encoding> -*-

This is the format originally from the Emacs editor, but according to PEP263 you can also use:

# vim: set fileencoding=<encoding>:

of even:

# coding=<encoding>

Where <encoding> can be any encoding that Python supports, but utf-8 is generally a good choice for portable code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM