Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Single string vs list of strings (http://www.velocityreviews.com/forums/t642567-single-string-vs-list-of-strings.html)

Scott Sharkey 10-30-2008 02:28 PM

Single string vs list of strings
 
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

Joe Strout 10-30-2008 03:10 PM

Re: Single string vs list of strings
 
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


greg 10-31-2008 08:54 AM

Re: Single string vs list of strings
 
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


All times are GMT. The time now is 05:28 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.