How do I distinguish a string from a sequence?
paul.moore at atosorigin.com
Fri Sep 28 15:43:28 CEST 2001
Yes, I know, a string is a sequence...
I'm thinking of writing a function which can take either a string, or a sequence
of strings, as an argument. A simplified example would be treating a single
string as a 1-tuple - something like
if # args is a string:
args = (args,)
for arg in args:
But I'm not sure how best to distinguish a string from a sequence - after all, a
string *is* a sequence. I want to avoid explicit type tests, as that seems prone
to errors (for a start, I should trap both strings and Unicode strings, and what
about 2.2 subclasses of strings?)
But I can't think of a suitable test.
The best I can come up with is a type-test along the lines of
if isinstance(args, type('')) or isinstance(args, type(u'')):
but as I say, that's annoyingly "explicit".
[If it matters, my "real" example is a popen-type function, which can take one
string argument - a command to execute - or a sequence of strings - a pipe
specification, where each element of the sequence would be a stage in the
Has anyone got any alternative suggestions?
More information about the Python-list