Single string vs list of strings

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Scott Sharkey

    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
  • Grant Edwards

    #2
    Re: Single string vs list of strings

    On 2008-10-30, Scott Sharkey <ssharkey@linux unlimited.comwr ote:
    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

    Comment

    • Joe Strout

      #3
      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

      Comment

      • greg

        #4
        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

        Comment

        Working...