美文网首页
python:#coding=utf-8 VS #coding

python:#coding=utf-8 VS #coding

作者: Yvettre | 来源:发表于2017-12-03 14:45 被阅读0次

Conclusion:

如果要在python2.x的文件中使用中文,则必须在第一行或者第二行写上注释,否则python2.x会默认使用ASCII编码。:

#coding=utf-8

或者:

# -*- coding:utf-8 -*- 

重点来了!!千万不能在第一种写法的等号两边加空格!!像这样:

Erroneous examples

发现坑的经过

打算把一个含有中文的长字符串写到txt文本中去,在定义这个字符串的时候就报错了。关键代码段如下:

#coding = utf-8
str_test = "这只是一个例子\nThis is an example"

报错信息如下:

SyntaxError: Non-ASCII character '\xe8' in file xx\xxxx.py on line xx, but no encoding declared; 

最后更改如下,就能正常运行了:

#coding=utf-8
str_test = "这只是一个例子\nThis is an example"

Additional remarks

参考python PEP,这个magic comment有以下几种写法:

# coding=<encoding name>

或者:

#!/usr/bin/python
# -*- coding: <encoding name> -*-

或者:

#!/usr/bin/python
# vim: set fileencoding=<encoding name> :

其实只要匹配如下的正则表达式就可以了:

^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)

相关文章

网友评论

      本文标题:python:#coding=utf-8 VS #coding

      本文链接:https://www.haomeiwen.com/subject/ffvabxtx.html