python中如何判断一个变量的数据类型?(原创)
import types
type(x) is types.IntType # 判断是否int 类型
type(x) is types.StringType #是否string类型
.........
--------------------------------------------------------
超级恶心的模式,不用记住types.StringType
import types
type(x) == types(1) # 判断是否int 类型
type(x) == type('a') #是否string类型
------------------------------------------------------
使用内嵌函数:
isinstance
(
object, classinfo
)
Return true if the object
argument is an instance
of the classinfo
argument, or of a (direct or indirect)
subclass thereof. Also return true if classinfo
is a type
object and object
is an object of that type. If object
is not a class instance or an object of the given type, the function
always returns false. If classinfo
is neither a class
object nor a type object, it may be a tuple of class or type objects,
or may recursively contain other such tuples (other sequence types are
not accepted). If classinfo
is not a class, type, or
tuple of classes, types, and such tuples, a TypeError
exception is raised. Changed in version
2.2: Support for a tuple of type information was added.
Python可以得到一个对象的类型 ,利用type函数:
>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>
不仅如此,还可以利用isinstance函数,来判断一个对象是否是一个已知的类型。
isinstance说明如下:
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass
thereof.
With a type as second argument, return whether that is the object's
type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut
for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类
相关文档:
前一篇文章写的在APACHE安装MOD_PYTHON的经过,其实挺简单,就是版本不兼容的问题.这次我大概说下部署DJANGO的过程.
先修改APACHE配置文件,使其加载mod_python模块
LoadModule python_module libexec/mod_python.so
运行命令查看
bin/httpd -M可以看到
python_module (shared)
Syntax OK
说明apache已经成功加 ......
当执行import
module时,解释器会根据下面的搜索路径,搜索module1.py文件。
1) 当前工作目录
2) PYTHONPATH中的目录
3) Python安装目录
(/usr/local/lib/python)
事实上,模块搜索是在保存在sys.path这个全局变量中的目录列表中进行搜索。
sys.path会在解释器开始执行时被初始化成包含:
1)当前工作目录
2) PYT ......
ubuntu10.05出来了这两天一直在折腾,显示wubi无反应,然后从硬盘安装期间又遇到grub错误等问题。安装成功后搞个中文输入法就老半天,最后使用Pinyin这个还算好用,有点想搜狗就是没什么词库。最恶心的还是vim的问题,用apt-get install vim装的vim不支持系统剪切板,只好从源代码编译,可是我尝试了很多次总是没有python支 ......
今天是第二天自己看关于Python了,看见一个Python2写的百度词典,我也用Python 3 写了一个。真的很小巧,呵呵,很好的语言。
不知道怎么上传代码格式的,就上传文本了:
# -*- coding: utf8 -*-
import urllib.parse
import urllib.request
def search(word):
#word = input("输入你要查询的 ......
当我们这样建立文件时
f =
file('x1.txt', 'w')
f.write(u'中文')
f.colse()
直
接结果应该是类似
f.write(u'中文')
UnicodeEncodeError: 'ascii'
codec can't encode characters in position 0-16: ordinal not in
range(128)
要直接写 utf-8 文件怎么办呢?
import codecs
f = codecs. ......