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

Jean-Paul Calderone exarkun at divmod.com
Thu Sep 21 10:25:32 EDT 2006


On Thu, 21 Sep 2006 09:26:20 -0500, Tim Chase <python.list at tim.thechases.com> wrote:
>> 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.

    >>> str is types.StringType
    True
    >>> unicode is types.UnicodeType
    True

Jean-Paul



More information about the Python-list mailing list