|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
AT&T devCentral & BlackBerry(r) Webcast Series: BlackBerry and GPS -Build Location Awareness into your BlackBerry Applications, July 10th-1:00PM EST. Register Today!
|
|
#1
|
|||
|
|||
|
Type Checking?
Ok here is what I am trying to do. I have a list and it has some strings in it, but it also has some lists in it. Once I grab an element from the list, how do I check if it is a list or a string, etc. Thanks!
|
|
#2
|
|||
|
|||
|
There are several ways:
Code:
>>> type([1, 2]) is list
True
>>> type([1, 2]) is str
False
>>> isinstance([1, 2], list)
True
>>> isinstance("text", basestring)
True
>>> isinstance("text", str)
True
>>> isinstance(u"text", str)
False
>>> isinstance(u"text", unicode)
True
A string can be of type str or of type unicode. Check if it's an instance of basestring instead. Last edited by percivall : April 1st, 2004 at 10:57 AM. |
|
#3
|
|||
|
|||
|
use the type(x) builtin function.
From the manual: Quote:
To check for strings it is safer to use isinstance(x, types.StringTypes), since that will succeed for both regular strings and unicode strings. Dave - The Developers' Coach Last edited by DevCoach : April 1st, 2004 at 11:01 AM. |
|
#4
|
|||
|
|||
|
Quote:
The pythonic way is to not check the type, but simply to do whatever actions you would do to the string and if any object happens to fit those criteria, allow it to do so. That way you can have string-like classes/objects that will also be usable in that function without having to constantly add special cases in your type checking. |
|
#5
|
|||
|
|||
|
Quote:
Good point. If you want to check the type of an object so that you can raise an exception if it not what you expect, then you are better off just using it and seeing what happens. However there are times when you do want to check the type so that you can take different actions depending on what the object is. A common case is to distinguish between strings and other sequence objects. Here is an example - a generator that converts a nested sequence into a flattened, non-nested sequence: Code:
import types
def flatten(seq):
if isinstance(seq, types.StringTypes):
yield seq
elif hasattr(seq, '__iter__'):
for item in seq:
for element in flatten(item):
yield element
else:
yield seq
>>> x = [['foo, bar', ('one', 'two', 'three')], ('four', 'five'), 4, (6,7)]
>>> list(flatten(x))
['foo, bar', 'one', 'two', 'three', 'four', 'five', 4, 6, 7]
>>>
If it did not check for a string before checking for a sequence then it would go into an infinite recursive loop, since the characters in a string are also strings. Dave - The Developers' Coach |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Type Checking? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|