Python string.lower() Examples

The following are 30 code examples for showing how to use string.lower(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: meddle   Author: glmcdona   File: inspect.py    License: MIT License 6 votes vote down vote up
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename 
Example 2
Project: ironpython2   Author: IronLanguages   File: debugger.py    License: Apache License 2.0 6 votes vote down vote up
def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args ):
    if module:
        keep = module.__name__
        keep = keep and (built_nodes.get(module) is None)
        if keep and hasattr(module, '__file__'):
            keep = string.lower(os.path.splitext(module.__file__)[1]) not in [".pyd", ".dll"]
#               keep = keep and module.__name__=='__main__'
    if module and keep:
#        print "keeping", module.__name__
        node = ModuleTreeNode(module)
        built_nodes[module] = node
        realNode = create_node_fn(*(node,)+create_node_args)
        node.realNode = realNode

        # Split into parent nodes.
        parts = string.split(module.__name__, '.')
        if parts[-1][:8]=='__init__': parts = parts[:-1]
        parent = string.join(parts[:-1], '.')
        parentNode = rootNode
        if parent:
            parentModule = sys.modules[parent]
            BuildModule(parentModule, built_nodes, rootNode, create_node_fn, create_node_args)
            if parentModule in built_nodes:
                parentNode = built_nodes[parentModule].realNode
        node.Attach(parentNode) 
Example 3
Project: ironpython2   Author: IronLanguages   File: testDCOM.py    License: Apache License 2.0 6 votes vote down vote up
def test(serverName):
    if string.lower(serverName)==string.lower(win32api.GetComputerName()):
        print "You must specify a remote server name, not the local machine!"
        return

    # Hack to overcome a DCOM limitation.  As the Python.Interpreter object
    # is probably installed locally as an InProc object, DCOM seems to ignore
    # all settings, and use the local object.
    clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER
    ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx)
    ob.Exec("import win32api")
    actualName = ob.Eval("win32api.GetComputerName()")
    if string.lower(serverName) != string.lower(actualName):
        print "Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName)
    else:
        print "Object created and tested OK on server '%s'" % serverName 
Example 4
Project: ironpython2   Author: IronLanguages   File: inspect.py    License: Apache License 2.0 6 votes vote down vote up
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename 
Example 5
Project: BinderFilter   Author: dxwu   File: inspect.py    License: MIT License 6 votes vote down vote up
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename 
Example 6
Project: Computable   Author: ktraunmueller   File: inspect.py    License: MIT License 6 votes vote down vote up
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename 
Example 7
Project: oss-ftp   Author: aliyun   File: inspect.py    License: MIT License 6 votes vote down vote up
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename 
Example 8
Project: pivy   Author: coin3d   File: SConsOptions.py    License: ISC License 6 votes vote down vote up
def diskcheck_convert(value):
    if value is None:
        return []
    if not SCons.Util.is_List(value):
        value = string.split(value, ',')
    result = []
    for v in map(string.lower, value):
        if v == 'all':
            result = diskcheck_all
        elif v == 'none':
            result = []
        elif v in diskcheck_all:
            result.append(v)
        else:
            raise ValueError(v)
    return result 
Example 9
Project: pivy   Author: coin3d   File: msvs.py    License: ISC License 6 votes vote down vote up
def printSources(self, hierarchy, commonprefix):
        sorteditems = hierarchy.items()
        # TODO(1.5):
        #sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
        sorteditems.sort(lambda a, b: cmp(string.lower(a[0]), string.lower(b[0])))

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.file.write('\t\t\t<Filter\n'
                                '\t\t\t\tName="%s"\n'
                                '\t\t\t\tFilter="">\n' % (key))
                self.printSources(value, commonprefix)
                self.file.write('\t\t\t</Filter>\n')

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)
                self.file.write('\t\t\t<File\n'
                                '\t\t\t\tRelativePath="%s">\n'
                                '\t\t\t</File>\n' % (file)) 
Example 10
Project: pmatic   Author: LarsMichelsen   File: inspect.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename 
Example 11
Project: Haystack   Author: lucapinello   File: bioutilities.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def read_sequence_from_fasta(fin, bpstart, bpend, line_length=50.0):
    bpstart=bpstart-1
    
    fin.seek(0)
    fin.readline()  #read the first line; the pointer is at the second line

    nbp = bpend - bpstart
    offset = int( bpstart + math.floor(bpstart/line_length)) #assuming each line contains 50 characters; add 1 offset per line
    
    if offset > 0:
        fin.seek(int(offset),1)

    seq = fin.read(nbp+int(math.floor(nbp/line_length))+1)
    seq = seq.replace('\n','')

    if len(seq) < nbp: 
        print 'Coordinate out of range:',bpstart,bpend
    
    return seq[0:nbp].lower() 
Example 12
Project: Haystack   Author: lucapinello   File: bioutilities.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def estimate_background(self):
        counting={'a':.0,'c':.0,'g':.0,'t':.0}
        all=0.0
        
        for chr_id in self.chr.keys():
            if self.verbose:
                print 'Counting on:',chr_id
            
            self.chr[chr_id].seek(0)
            self.chr[chr_id].readline()
            
            for line in self.chr[chr_id]:
                for nt in counting.keys():
                    count_nt=line.lower().count(nt)
                    counting[nt]+=count_nt
                    all+=count_nt
        
        if self.verbose:
            print counting
        
        for nt in counting.keys():
            counting[nt]/=all
            
        return counting 
Example 13
Project: Haystack   Author: lucapinello   File: bioutilities.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def estimate_background(self):
        counting={'a':.0,'c':.0,'g':.0,'t':.0}
        all=0.0
        
        for chr_id in self.genome.keys():
            if self.verbose:
                start_time = time.time()
                print 'Counting on:',chr_id

            for nt in counting.keys():
                
                count_nt=self.genome[chr_id][:].lower().count(nt)
                counting[nt]+=count_nt
                all+=count_nt

            print 'elapsed:',time.time() - start_time
        
        if self.verbose:
            print counting

        for nt in counting.keys():
            counting[nt]/=all
        
        return counting 
Example 14
Project: iSDX   Author: sdn-ixp   File: tnode.py    License: Apache License 2.0 5 votes vote down vote up
def base36(s):
    n = 0
    for c in string.lower(s):
        if c.isdigit():
            n = n * 36 + ord(c) - ord('0')
            continue
        if c.isalpha():
            n = n * 36 + ord(c) - ord('a') + 10
            continue
        n = n * 36 + 35  #treat everything else as a 'z'
    return n 
Example 15
Project: iSDX   Author: sdn-ixp   File: tmgr.py    License: Apache License 2.0 5 votes vote down vote up
def base36(s):
    n = 0
    for c in string.lower(s):
        if c.isdigit():
            n = n * 36 + ord(c) - ord('0')
            continue
        if c.isalpha():
            n = n * 36 + ord(c) - ord('a') + 10
            continue
        n = n * 36 + 35  #treat everything else as a 'z'
    return n 
Example 16
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def equalsIgnoreCase(a, b):
    """Return true iff a and b have the same lowercase representation.
    
    >>> equalsIgnoreCase('dog', 'Dog')
    1
    >>> equalsIgnoreCase('dOg', 'DOG')
    1
    """
    # test a == b first as an optimization where they're equal
    return a == b or string.lower(a) == string.lower(b)


#
# Sequence Utility Functions
# 
Example 17
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getWord(self, form, line=None):
	key = string.replace(string.lower(form), ' ', '_')
	pos = self.pos
	def loader(key=key, line=line, indexFile=self.indexFile):
	    line = line or indexFile.get(key)
	    return line and Word(line)
	word = _entityCache.get((pos, key), loader)
	if word:
	    return word
	else:
	    raise KeyError, "%s is not in the %s database" % (`form`, `pos`) 
Example 18
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _equalsIgnoreCase(a, b):
    """Return true iff a and b have the same lowercase representation.
    
    >>> _equalsIgnoreCase('dog', 'Dog')
    1
    >>> _equalsIgnoreCase('dOg', 'DOG')
    1
    """
    return a == b or string.lower(a) == string.lower(b)

#
# File utilities
# 
Example 19
Project: razzy-spinner   Author: rafasashi   File: porter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def adjust_case(self, word, stem):
        lower = string.lower(word)

        ret = ""

        for x in xrange(len(stem)):
            if lower[x] == stem[x]:
                ret = ret + word[x]
            else:
                ret = ret + stem[x]

        return ret

    ## --NLTK--
    ## Don't use this procedure; we want to work with individual
    ## tokens, instead.  (commented out the following procedure)
    #def stem(self, text):
    #    parts = re.split("(\W+)", text)
    #    numWords = (len(parts) + 1)/2
    #    
    #    ret = ""
    #    for i in xrange(numWords):
    #        word = parts[2 * i]
    #        separator = ""
    #        if ((2 * i) + 1) < len(parts):
    #            separator = parts[(2 * i) + 1]
    #
    #        stem = self.stem_word(string.lower(word), 0, len(word) - 1)
    #        ret = ret + self.adjust_case(word, stem)
    #        ret = ret + separator
    #    return ret

    ## --NLTK--
    ## Define a stem() method that implements the StemmerI interface. 
Example 20
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def equalsIgnoreCase(a, b):
    """Return true iff a and b have the same lowercase representation.
    
    >>> equalsIgnoreCase('dog', 'Dog')
    1
    >>> equalsIgnoreCase('dOg', 'DOG')
    1
    """
    # test a == b first as an optimization where they're equal
    return a == b or string.lower(a) == string.lower(b)


#
# Sequence Utility Functions
# 
Example 21
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getWord(self, form, line=None):
	key = string.replace(string.lower(form), ' ', '_')
	pos = self.pos
	def loader(key=key, line=line, indexFile=self.indexFile):
	    line = line or indexFile.get(key)
	    return line and Word(line)
	word = _entityCache.get((pos, key), loader)
	if word:
	    return word
	else:
	    raise KeyError, "%s is not in the %s database" % (`form`, `pos`) 
Example 22
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _equalsIgnoreCase(a, b):
    """Return true iff a and b have the same lowercase representation.
    
    >>> _equalsIgnoreCase('dog', 'Dog')
    1
    >>> _equalsIgnoreCase('dOg', 'DOG')
    1
    """
    return a == b or string.lower(a) == string.lower(b)

#
# File utilities
# 
Example 23
Project: mishkal   Author: linuxscout   File: datetimeutil.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parse_timedelta(val):
    """
    returns a ``timedelta`` object, or None
    """
    if not val:
        return None
    val = string.lower(val)
    if "." in val:
        val = float(val)
        return timedelta(hours=int(val), minutes=60*(val % 1.0))
    fHour = ("h" in val or ":" in val)
    fMin  = ("m" in val or ":" in val)
    fFraction = "." in val
    for noise in "minu:teshour()":
        val = string.replace(val, noise, ' ')
    val = string.strip(val)
    val = string.split(val)
    hr = 0.0
    mi = 0
    val.reverse()
    if fHour:
        hr = int(val.pop())
    if fMin:
        mi = int(val.pop())
    if len(val) > 0 and not hr:
        hr = int(val.pop())
    return timedelta(hours=hr, minutes=mi) 
Example 24
Project: mishkal   Author: linuxscout   File: datetimeutil.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parse_time(val):
    if not val:
        return None
    hr = mi = 0
    val = string.lower(val)
    amflag = (-1 != string.find(val, 'a'))  # set if AM is found
    pmflag = (-1 != string.find(val, 'p'))  # set if PM is found
    for noise in ":amp.":
        val = string.replace(val, noise, ' ')
    val = string.split(val)
    if len(val) > 1:
        hr = int(val[0])
        mi = int(val[1])
    else:
        val = val[0]
        if len(val) < 1:
            pass
        elif 'now' == val:
            tm = localtime()
            hr = tm[3]
            mi = tm[4]
        elif 'noon' == val:
            hr = 12
        elif len(val) < 3:
            hr = int(val)
            if not amflag and not pmflag and hr < 7:
                hr += 12
        elif len(val) < 5:
            hr = int(val[:-2])
            mi = int(val[-2:])
        else:
            hr = int(val[:1])
    if amflag and hr >= 12:
        hr = hr - 12
    if pmflag and hr < 12:
        hr = hr + 12
    return time(hr, mi) 
Example 25
Project: meddle   Author: glmcdona   File: util.py    License: MIT License 5 votes vote down vote up
def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = string.lower(val)
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError, "invalid truth value %r" % (val,) 
Example 26
Project: meddle   Author: glmcdona   File: pydoc.py    License: MIT License 5 votes vote down vote up
def interact(self):
        self.output.write('\n')
        while True:
            try:
                request = self.getline('help> ')
                if not request: break
            except (KeyboardInterrupt, EOFError):
                break
            request = strip(replace(request, '"', '', "'", ''))
            if lower(request) in ('q', 'quit'): break
            self.help(request) 
Example 27
Project: meddle   Author: glmcdona   File: pydoc.py    License: MIT License 5 votes vote down vote up
def run(self, callback, key=None, completer=None, onerror=None):
        if key: key = lower(key)
        self.quit = False
        seen = {}

        for modname in sys.builtin_module_names:
            if modname != '__main__':
                seen[modname] = 1
                if key is None:
                    callback(None, modname, '')
                else:
                    desc = split(__import__(modname).__doc__ or '', '\n')[0]
                    if find(lower(modname + ' - ' + desc), key) >= 0:
                        callback(None, modname, desc)

        for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
            if self.quit:
                break
            if key is None:
                callback(None, modname, '')
            else:
                loader = importer.find_module(modname)
                if hasattr(loader,'get_source'):
                    import StringIO
                    desc = source_synopsis(
                        StringIO.StringIO(loader.get_source(modname))
                    ) or ''
                    if hasattr(loader,'get_filename'):
                        path = loader.get_filename(modname)
                    else:
                        path = None
                else:
                    module = loader.load_module(modname)
                    desc = (module.__doc__ or '').splitlines()[0]
                    path = getattr(module,'__file__',None)
                if find(lower(modname + ' - ' + desc), key) >= 0:
                    callback(path, modname, desc)

        if completer:
            completer() 
Example 28
Project: meddle   Author: glmcdona   File: inspect.py    License: MIT License 5 votes vote down vote up
def getinnerframes(tb, context=1):
    """Get a list of records for a traceback's frame and all lower frames.

    Each record contains a frame object, filename, line number, function
    name, a list of lines of context, and index within the context."""
    framelist = []
    while tb:
        framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
        tb = tb.tb_next
    return framelist 
Example 29
Project: Webshell-Sniper   Author: WangYihang   File: shell.py    License: GNU General Public License v3.0 5 votes vote down vote up
def interactive(self):
        Log.info("Starting interactive shell...")
        while True:
            Log.context("sniper")
            Log.context("shell")
            command = raw_input("$ ")
            if string.lower(command) == "exit":
                Log.info("Exiting shell...")
                break
            result = self.webshell.auto_exec(command)
            if result[0]:
                Log._print(result[1])
            else:
                Log.error(result[1]) 
Example 30
Project: bitmask-dev   Author: leapcode   File: pixelizer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_mail(self, mailbox_name, raw_msg):
            name = yield self._get_case_insensitive_mbox(mailbox_name)
            mailbox = yield self.account.get_collection_by_mailbox(name)
            flags = ['\\Recent']
            if mailbox_name.lower() == 'sent':
                flags += '\\Seen'
            message = yield mailbox.add_msg(raw_msg, tuple(flags))

            # this still needs the pixelated interface because it does stuff
            # like indexing the mail in whoosh, etc.
            mail = yield self._leap_message_to_leap_mail(
                message.get_wrapper().mdoc.doc_id, message, include_body=True)
            defer.returnValue(mail)