How to return an "not string' error in function?

Tim Chase python.list at tim.thechases.com
Thu Sep 21 10:26:20 EDT 2006


> def test(s):
>        if type(s) != ? :
>           return
> #So here I want establish a situation about that if <s> is not string
> #then <return>, but how should write the <?> ?
> #Or is there any other way to do it?

 >>> isinstance("hello", basestring)
True
 >>> isinstance(u"hello", basestring)
True

This will return true for both regular strings and for unicode 
strings.  If that's a problem, you can use

 >>> import types
 >>> isinstance("hello", types.StringType)
True
 >>> isinstance(u"hello", types.StringType)
False
 >>> isinstance("hello", types.UnicodeType)
False
 >>> isinstance(u"hello", types.UnicodeType)
True

...or, if you don't want to qualify them with "types." each time, 
you can use

 >>> from types import StringType, UnicodeType

to bring them into the local namespace.

HTH,

-tkc









More information about the Python-list mailing list