python出现SyntaxError: Non-ASCII character '\xe6' in file 打印日期.py on line 1, but no encoding declared;

刚开始学习python,照着书上敲的代码:

#根据给定的年月日以数字的形式打印出来
months = [
     'January',
     'Febuary',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December'
]

#以1~31的数字作为结尾的列表
endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
        + ['st', 'nd', 'rd'] + 7 * ['th'] \
        + ['st']

year    = raw_input('Year: ')
month   = raw_input('Month (1-12): ')
day     = raw_input('Day (1-31)')

month_number = int(month)
day_number = int(day)

#记得要将月份和天数减1,以获得正确的索引
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]

print month_name + ' ' + ordinal + ', ' + year
~                                           

执行时出现了错误:

SyntaxError: Non-ASCII character '\xe6' in file 打印日期.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details


百度了一下:

发现是因为Python在默认状态下不支持源文件中的编码所致。解决方案有如下三种:

一、在文件头部添加如下注释码:

 # coding= 例如,可添加# coding=utf-8

二、在文件头部添加如下两行注释码:

#!/usr/bin/python

# -*- coding: -*- 例如,可添加# -*- coding: utf-8 -*-

三、在文件头部添加如下两行注释码:

 #!/usr/bin/python

# vim: set fileencoding= : 例如,可添加# vim: set fileencoding=utf-8 :


我用的是第一种方法解决的!记录一下。


你可能感兴趣的:(Python)