python使用 UTF-8编码
来源:互联网 发布:河北省网络行政学院 编辑:程序博客网 时间:2024/06/05 08:02
Python 使用 UTF-8 编码
版权信息: 可以任意转载, 转载时请务必以超链接形式标明文章原文出处, 即下面的声明.
原文出处:http://blog.chenlb.com/2010/01/python-use-utf-8.html
一般我喜欢用 utf-8 编码,在 python 怎么使用呢?
1、在 python 源码文件中用 utf-8 文字。一般会报错,如下:
File "F:\workspace\psh\src\test.py", line 2
SyntaxError: Non-ASCII character '\xe4' in file F:\workspace\psh\src\test.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
test.py 的内容:
- print "你好"
如果要正常运行在 test.py 文件前面加编码注释,如:
- #!/usr/bin/python2.6
- # -*- coding: utf-8 -*-
- print "你好"
2、
python 对 url encode UTF-8 怎么做呢?
windows 的命令行参数转 utf-8 怎么做呢?
代码:
- # -*- coding: utf-8 -*-
- import urllib
- import sys
- if __name__ == '__main__':
- if len(sys.argv) > 1:
- str = sys.argv[1]
- str = unicode(str, 'gbk')
- else:
- str = "中文"
- print str
- params = {}
- params['name'] = str.encode("UTF-8")
- print urllib.urlencode(params)
python 内部是用 unicode 吧。
由于 windows 的命令行输入的是 GBK 编码的,可以要先转为 unicode(第三8行)。
要转 url encode 时,先把 str 转为 utf-8。
默认的输出结果:
中文
name=%E4%B8%AD%E6%96%87
写 python 脚本来做写小事情方便,比如要取些 solr 的数据,solr 的 url 编码是 utf-8 的。
参考:http://evanjones.ca/python-utf8.html
- Python 使用 UTF-8 编码
- python使用 UTF-8编码
- Python编码和UTF-8
- Python 编码 Unicode utf-8
- Python MySQLdb 使用utf-8 编码插入中文数据
- Python MySQLdb 使用utf-8 编码插入中文数据
- Python MySQLdb 使用utf-8 编码插入中文数据
- Python MySQLdb 使用utf-8 编码插入中文数据
- Netbeans使用UTF-8编码
- python 之编码转换 unicode, utf-8, utf-16, GBK
- python 编码 问题 UTF-8 unicode
- Python的编码注释# -*- coding:utf-8 -*-
- python 关于UTF-8 编码的问题
- Python的编码注释# -*- coding:utf-8 -*-
- python设置utf-8为默认编码
- Python笔记:字符编码unicode/utf-8
- python 之 utf-8编码的秘密
- python 中文编码 #-*-coding:utf-8-*-
- 摆花
- Python: 创建空的list,以及append用法
- TCP协议原理详解
- 数据离散化模板(用STL实现)
- 谈谈谷歌word2vec的原理
- python使用 UTF-8编码
- 机翼的翼型和升力
- 洛谷p2239 螺旋矩阵
- 动态规划
- vue组件中$emit()的作用
- 0-1背包问题
- 链接器
- DOM文档对象模型
- 【PAT】【Advanced Level】1063. Set Similarity (25)