Is there any way to say ignore case with "in"?

ijoshua ijoshua at gmail.com
Sun Apr 6 11:19:38 EDT 2008


On Apr 5, 7:14 am, Steve Holden <st... at holdenweb.com> wrote:
> 7stud wrote:
>
> > Easier?  You mean like some kind of mind meld?
>
> That's right, DWIM mode Python. Rock on!

If it is common enough, define a custom type of string.  I have
appended a simple version that should work for your example of `in`.
You would probably want to define all of the builtin str methods for
this class to be really useful.

Regards,
Josh

---
# cistr.py

import operator

class cistr(object):
    """A type of string that ignores character
case
    for the right side of the `in`
operator.

    >>> 'AND' in cistr('sPaM aNd
eGgS')
 
True
    """
    def __init__(self, string):
        self.string = str(string).lower()

    def __contains__(self, other):
        return operator.contains(self.string, other.lower())

    def __repr__(self):
        return 'cistr(%r)'%(self.string)

    def lower(self):
        return self.string

if '__main__' == __name__:
    string1 = 'AND'
    string2 = 'sPaM aNd eGgS'
    print '%r in %r ? %r' % (string1, string2, string1 in string2)
    print '%r in %r ? %r' % (string1, cistr(string2), string1 in
cistr(string2))




More information about the Python-list mailing list