By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,513 Members | 1,840 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,513 IT Pros & Developers. It's quick & easy.

Single string vs list of strings

P: n/a
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
Oct 30 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On 2008-10-30, Scott Sharkey <ss******@linuxunlimited.comwrote:
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?
>>type('asdf') is list
False
>>type(['asdf','qwer']) is list
True

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.
>>type('asdf') is str
True

Checking to see if something is a sequence of strings is a bit
trickier, since a string is actually a sequence of strings.
You first have to verify that it's not a string, and then check
for the API that you're going to use (iteration or indexing).

--
Grant Edwards grante Yow! I represent a
at sardine!!
visi.com
Oct 30 '08 #2

P: n/a
On Oct 30, 2008, at 8:55 AM, Grant Edwards wrote:
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.
>>>type('asdf') is str
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

Oct 30 '08 #3

P: n/a
Grant Edwards wrote:
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.

--
Greg
Oct 31 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.