在Python源码中使用utf-8编码 [英] Working with utf-8 encoding in Python source

查看:214
本文介绍了在Python源码中使用utf-8编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


s = u.encode('utf-8')
print s
$ python bla.py
文件bla.py,第1行
SyntaxError:第1行文件bla.py中的非ASCII字符'\xe2',但未声明编码;有关详细信息,请参阅http://www.python.org/peps/pep-0263.html

我可以在源代码中声明utf-8字符串?

解决方案

在源头中可以声明:

 #!/ usr / bin / env python 
# - * - 编码:utf-8 - * -
....

它在 PEP 0263



然后,您可以在字符串中使用UTF-8:

 #!/ usr / bin / env python 
# - * - 编码:utf-8 - * -

u =
$ b = uu.encode('cp1250')
打印

这个声明在Python 3中不是必需的,因为 UTF-8 是默认的源代码请参阅 PEP 3120 )。


$ cat bla.py 
u = unicode('d…')
s = u.encode('utf-8')
print s
$ python bla.py 
  File "bla.py", line 1
SyntaxError: Non-ASCII character '\xe2' in file bla.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

How can I declare utf-8 strings in source code?

解决方案

In source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie wąż wąską dróżką'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

这篇关于在Python源码中使用utf-8编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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