Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Single string vs list of strings

Thread Tools

Single string vs list of strings

Scott Sharkey
Posts: 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?

Reply With Quote
Joe Strout
Posts: 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'.

- Joe

Reply With Quote
Posts: 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.

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Memory issues when storing as List of Strings vs List of List OW Ghim Siong Python 2 11-30-2010 12:22 PM
Strings, Strings and Damned Strings Ben C Programming 14 06-24-2006 05:09 AM
How to generate k+1 length strings from a list of k length strings? Girish Sahani Python 17 06-09-2006 11:01 AM
Asp.NET Javascript string, want to pass '(single quotes' within '(single quotes) Chris ASP .Net 1 03-24-2006 09:03 PM
convert list of strings to set of regexes; convert list of strings to trie Klaus Neuner Python 7 07-26-2004 07:25 AM