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

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

问题描述

$ 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

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

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

推荐答案

b

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

PEP 0263

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

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)

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

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