问题:
需要判断一个对象,或者方法的一个参数,看它们是否是字符串.
解决方法:
判断一个对象是否是字符串或者unicode串的最简单有效的办法是使用isinstance和basestring
def isAString(anobj):
return isinstance(anobj, basestring)
一般的说,判断一个对象是否是字符串,最容易想到的方法是:
def isString(str):
return type(str) is type('')
这样有一些缺点:无法判断unicode字符串,或者用户从basestring继承下来的字符串类型.
当然,上面的算法在有些情况下也会失效:如Python类库中的UserString
那样,可以使用下面的算法:
def isStringLike(str):
try: str + ''
except: return False
else: return True
这样的算法会降低方法的效率,但能适应更多的情况.
相关说明:
class basestring(object)
| Type basestring cannot be instantiated; it is the base for str and unicode.
|
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object at 0x8147420>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
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.).
class type(object)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
分享到:
相关推荐
PythonCookbook3高清.pdf
这是 Python Cookbook 英文版的,需要的拿走吧
绍了Python应用在各个领域中的一些使用技巧和方法,从最基本的字符、文件序列、字典和排序,到进阶的面向对象编程、数据库和数据持久化、XML处理和Web编程,再到比较高级和抽象的描述符、装饰器、元类、迭代器和生成...
Python Cookbook.pdf
Modern Python Cookbook
Python Cookbook(第3版)中文版.pdf 极清PDF
15.15 C字符串转换为Python字符串 15.16 不确定编码格式的C字符串 15.17 传递文件名给C扩展 15.18 传递已打开的文件给C扩展 15.19 从C语言中读取类文件对象 15.20 处理C语言中的可迭代对象 15.21 诊断分析...
Python Cookbook, 2nd Edition, Python Cookbook, 2nd Edition, Python Cookbook, 2nd Edition
python cookbook 3th python cookbook 3th python cookbook 3th python cookbook 3th
Modern Python Cookbook 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开
PythonCookbook.zip
python cookbook(第3版)高清中文完整版
python cookbook(第3版)高清中文完整版.pdf,作者: David Beazley, Brian K. Jones 译者: 熊能 版本: 第3版 出版社: O’Reilly Media, Inc. 出版日期: 2013年5月08日 Copyright © 2013 David Beazley and ...
另外,每个示例都只是一个入门指导,如果读者想深入研究,需要自己去查阅更多资料。因此,我们假定读者可以很熟练的使用搜索引擎以及知道怎样查询在线的 Python 文档。 这本书不适合 Python 的初学者。事实上,本书...
Python CookBook 3rd Edition, epub type file
Python Cookbook.chm是一本全面的、详尽的Python英文教程。
python cookbook 英文 python cookbook 英文
这本独特的食谱包含了用Python 3.3编写和测试的实用食谱,适合有经验的Python程序员,他们希望专注于现代工具和习惯用法。
python cookbook 食谱 一条一条的解释,不错
python cookbook 中文版,欢迎python爱好者进行下载,谢谢