非ASCII字符错误python

时间:2014-10-11 18:18:02

标签: python-2.7 non-ascii-characters

我是一个初学程序员,试图编写一个生成随机密码的python脚本。但是,即使我声明编码#utf-8,我总是得到一个非ASCII字符错误,如Stack Overflow中另一个类似的问题所述。这是源代码:

import string
import random
#coding: utf-8
print "Password generator will create a random customizable password."
print "Choose your options wisely."
number = int(input("How many letters do you want in your password?"))
caps = str(input("Do you want capital letters in your password? Y/N"))
symbols = str(input( "Do you want punctuation, numbers and other symbols in your password? Y/N"))
punctuation = ("!", ".", ":", ";", ",", "?", "'", "@", "£", "$", "«", "»", "~", "^","%", "#", "&", "/", range(0, 11))
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
if caps == "N":
    characters = lowercase
else:
    characters = uppercase + lowercase
if symbols == "Y":
    characters += punctuation
password = random.sample(characters, number)
print "The password is", password "."

这是终端输出

pedro @ pedro-Inspiron-3521:〜/桌面$ python passwordgenerator.py

文件" passwordgenerator.py",第9行 SyntaxError:非ASCII字符' \ xc2'在第9行的文件passwordgenerator.py中,但没有声明编码;有关详细信息,请参阅http://www.python.org/peps/pep-0263.html

我检查了链接,但我无法理解一件事,也许是因为我不是母语为英语的人,因为我不久前开始编程。谢谢你的帮助。

3 个答案:

答案 0 :(得分:5)

#coding: utf-8行必须位于文件的顶部才能允许使用非ASCII字符。

£«»不是ASCII。

虽然您可能不希望密码中包含非ascii字符,并且在大多数网站上都不允许使用非ascii字符,但理论上没有理由不允许这样做。

答案 1 :(得分:2)

您的标点符号列表中有>><<个符号。

这些无效。尝试找到他们的unicode代码

http://www.fileformat.info/info/unicode/char/bb/index.htm http://www.fileformat.info/info/unicode/char/ab/index.htm

修改: 哦,等等,这是一个密码生成器,所以NO甚至不把双V形符号作为标点符号列表的一部分,因为它们在任何密码中都无效。

punctuation = ("!", ".", ":", ";", ",", "?", "'", "@", "$", "~", "^", "%", "#", "&", "/", range(0, 11))

另外,为什么要在标点符号元组中添加数字?

为什么不使用string.punctuation和string.digits?

答案 2 :(得分:0)

如果您使用的是Mac,则会有文件.DS_STORE,在读取文件夹内容时会导致ascii错误。

如果您使用的是Mac

,请执行以下操作
  • 删除所有DS_Store文件

  • 选择应用程序&gt;公用事业公司推出终端。

  • 输入以下UNIX命令:

  • sudo find / -name“.DS_Store”-depth -exec rm {} \;

  • 提示输入密码时,请输入Mac OS X管理员 密码

相关问题