Single string vs list of strings

Discussion in 'Python' started by Scott Sharkey, Oct 30, 2008.

  1. 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
     
    Scott Sharkey, Oct 30, 2008
    #1
    1. Advertising

  2. Scott Sharkey

    Joe Strout Guest

    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
     
    Joe Strout, Oct 30, 2008
    #2
    1. Advertising

  3. Scott Sharkey

    greg Guest

    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
     
    greg, Oct 31, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris
    Replies:
    1
    Views:
    13,748
    Oisin
    Mar 24, 2006
  2. Klaus Neuner
    Replies:
    7
    Views:
    527
    Klaus Neuner
    Jul 26, 2004
  3. Girish Sahani
    Replies:
    17
    Views:
    586
    Boris Borcic
    Jun 9, 2006
  4. Ben

    Strings, Strings and Damned Strings

    Ben, Jun 22, 2006, in forum: C Programming
    Replies:
    14
    Views:
    810
    Malcolm
    Jun 24, 2006
  5. OW Ghim Siong
    Replies:
    2
    Views:
    422
    Peter Otten
    Nov 30, 2010
Loading...

Share This Page