何时使用utf8作为py文件中的标头 [英] When to use utf8 as a header in py files

查看:81
本文介绍了何时使用utf8作为py文件中的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下载的代码中获取的某些源文件具有以下标头

Some source files, from downloaded code, have the following header

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

我知道utf-8编码是什么,但是为什么要在python源文件中将其作为标头使用?

I have an idea what utf-8 encoding is but why would it be needed as a header in a python source file?

推荐答案

您需要在不是来自于ascii的代码字符中使用的任何地方,例如:

wherever you need to use in your code chars that aren't from ascii, like:

ă 

口译员会抱怨说他不理解那个字符.

interpreter will complain that he doesn't understand that char.

通常在定义常量时会发生这种情况.

Usually this happens when you define constants.

示例: 添加到x.py

Example: Add into x.py

print 'ă'

然后启动python控制台

then start a python console

import x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "x.py", line 1
 SyntaxError: Non-ASCII character '\xc4' in file x.py on line 1, 
   but no encoding declared;
   see http://www.python.org/peps/pep-0263.html for details

这篇关于何时使用utf8作为py文件中的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆