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
basestring
instead ofstr
?You should check for
basestring
instead ofstr
since it's a common class from which both thestr
andunicode
types inherit from. Checking only thestr
leaves out theunicode
types.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
list
instead ofnot isinstance(lst, basestring)
, the code would get rewritten as.Moving away from one liners, we could use.