Single string vs list of strings

S

Scott Sharkey

Hi All,

I have a need to determine whether a passed variable is a single string,
or a list of strings. What is the most pythonic way to do this?

Thanks.
-Scott
 
J

Joe Strout

The question you might want to asked is whether the parameter
is a single string or a sequence of strings. That way your
code will also work with an iterator that returns strings.

True

I agree with the general approach, but this test will fail for Unicode
strings, and so is probably bad mojo moving forward. Instead I suggest:

isinstance(x, basestring)

which will work whether x='asdf' or x=u'asdf'.

Best,
- Joe
 
G

greg

Grant said:
Checking to see if something is a sequence of strings is a bit
trickier, since a string is actually a sequence of strings.

For that reason I'd just check whether it's a string,
and if it's anything else, assume it's a sequence of
strings. You'll find out soon enough if it doesn't
support indexing or iterating or whatever you want to
do with it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top