How to check if an object is a list of strings? I could only check if an object is string as such:
def checktype(obj):
if isinstance(obj,str):
print "It's a string"
obj1 = ['foo','bar','bar','black','sheet']
obj2 = [1,2,3,4,5,'bar']
obj3 = 'bar'
for i in [obj1,obj2,obj3]:
checktype(i)
Desired output:
It's a list of strings
It's not a list of strings or a single string
It's a single string
Something like this, I presume? You could do some checks to see if it's a single string.
Why check for
basestringinstead ofstr?You should check for
basestringinstead ofstrsince it's a common class from which both thestrandunicodetypes inherit from. Checking only thestrleaves out theunicodetypes.As per Steven Rumbalski's suggestions, if you need to specifically check for a list of strings, you could do.
EDIT - As per abarnert's suggestion, you could also check for a
listinstead ofnot isinstance(lst, basestring), the code would get rewritten as.Moving away from one liners, we could use.