partial / wildcard string match in 'in' and 'list.index()'

Discussion in 'Python' started by Jon Perez, May 28, 2004.

  1. Jon Perez

    Jon Perez Guest

    For a given list:

    fruits=["apples","oranges","mangoes","bananas"]




    Is it possible to do wildcard matches like shown below?

    1. "man*" in fruits

    2. fruits.index("man*")

    3. "*nanas*" in fruits

    4. fruits.index("*nanas")



    or is there any way to achieve an equivalent effect
    short of doing a while loop?
     
    Jon Perez, May 28, 2004
    #1
    1. Advertising

  2. Jon Perez

    Peter Otten Guest

    Jon Perez wrote:

    > For a given list:
    >
    > fruits=["apples","oranges","mangoes","bananas"]
    >
    >
    >
    >
    > Is it possible to do wildcard matches like shown below?
    >
    > 1. "man*" in fruits
    >
    > 2. fruits.index("man*")
    >
    > 3. "*nanas*" in fruits
    >
    > 4. fruits.index("*nanas")
    >
    >
    >
    > or is there any way to achieve an equivalent effect
    > short of doing a while loop?


    >>> import fnmatch
    >>> def find(seq, pattern):

    .... pattern = pattern.lower()
    .... for i, n in enumerate(seq):
    .... if fnmatch.fnmatch(n.lower(), pattern):
    .... return i
    .... return -1
    ....
    >>> def index(seq, pattern):

    .... result = find(seq, pattern)
    .... if result == -1:
    .... raise ValueError
    .... return result
    ....
    >>> def contains(seq, pattern):

    .... return find(seq, pattern) != -1
    ....
    >>> fruit = "apples oranges mangoes bananas".split()
    >>> contains(fruit, "man*")

    True
    >>> contains(fruit, "*nas")

    True
    >>> index(fruit, "*ANA*")

    3
    >>> find(fruit, "*")

    0
    >>> find(fruit, "m*s")

    2
    >>> find(fruit, "m*x")

    -1
    >>>


    If you want case-sensitive matches, use fnmatchcase() and remove the
    ..lower() conversions.

    Peter
     
    Peter Otten, May 28, 2004
    #2
    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. Bruce Lawson

    [ ] (Wildcard - Character(s) to Match) ?

    Bruce Lawson, Apr 19, 2006, in forum: ASP .Net
    Replies:
    1
    Views:
    460
    Karl Seguin [MVP]
    Apr 19, 2006
  2. Patrick  Hall
    Replies:
    2
    Views:
    2,126
    Josiah Carlson
    Jun 4, 2004
  3. Mr.SpOOn

    wildcard match with list.index()

    Mr.SpOOn, Nov 10, 2008, in forum: Python
    Replies:
    4
    Views:
    305
    Sion Arrowsmith
    Nov 19, 2008
  4. Replies:
    7
    Views:
    879
  5. Tomasz Chmielewski

    sorting index-15, index-9, index-110 "the human way"?

    Tomasz Chmielewski, Mar 4, 2008, in forum: Perl Misc
    Replies:
    4
    Views:
    337
    Tomasz Chmielewski
    Mar 4, 2008
Loading...

Share This Page