`

Python Cookbook 1.3 测试一个对象是否是字符串

阅读更多
问题:
需要判断一个对象,或者方法的一个参数,看它们是否是字符串.

解决方法:
判断一个对象是否是字符串或者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 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics