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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值