Thread: Question

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Posts
    136
    Rep Power
    10

    Question


    Code:
    nicks = ["Hei", "bjaRne", "Roar", "Ernst"]
    if "BJARne" in nicks:
        print "Yes"

    How do I make this print "Yes"(I *want* this to print Yes), I've made a chat server, and if I call myself for "Dag" I do not want someone else to be able to call themself for "dag" or "daG" or "dAg" or "dAG"..
    Maybe I'm just tired now, but I can't think out a good solution for this...

    I know I of course can do:

    Code:
    for n in nicks:
        if "BJARne".lower() == n.lower():
            print "Yes"
    but isn't there any other way which is not so many lines or builtin function for this?

    also I can't really use the above for the reason that it has to be checked in a elif block, and then the elif first has to be true..

    anyone got suggestions?

    best regards
    Dag Hansteen
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Ensure that all the values in the list 'nicks' are in lower case, then you only have to call the 'lower' method on the input string, not on both sides of the test. Python does not have a built-in case insensitive comparison for strings. e.g.:
    Code:
    nicks = [x.lower() for x in ("Hei", "bjaRne", "Roar", "Ernst")]
    
    if "BJARne".lower() in nicks:
        print "Yes"
    If the list of nicks is going to be large then it will be more efficient to use a set instead of a list, since the test 'if x in list' does a linear search through the list, but 'if x in set' does a single hash table lookup. e.g.
    Code:
    from sets import Set
    nicks = Set([x.lower() for x in ("Hei", "bjaRne", "Roar", "Ernst")])
    
    if "BJARne".lower() in nicks:
        print "Yes"
    The above code is for Python 2.3 - in 2.4 there is a built-in set type, and you can replace the list comprehension with a generator expression.

    Dave - The Developers' Coach

IMN logo majestic logo threadwatch logo seochat tools logo