我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.index()。
def compile_repl_group(source, pattern): "Compiles a replacement template group reference." source.expect("<") name = parse_name(source, True, True) source.expect(">") if name.isdigit(): index = int(name) if not 0 <= index <= pattern.groups: raise error("invalid group reference", source.string, source.pos) return index try: return pattern.groupindex[name] except KeyError: raise IndexError("unknown group") # The regular expression is parsed into a syntax tree. The different types of # node are defined below.
def at_end(self): string = self.string pos = self.pos try: if self.ignore_space: while True: if string[pos].isspace(): pos += 1 elif string[pos] == "#": pos = string.index("\n", pos) else: break return pos >= len(string) except IndexError: # We've reached the end of the string. return True except ValueError: # The comment extended to the end of the string. return True
def _defaultButton(self): defaultbutton = self['defaultbutton'] if self.oldDefault == defaultbutton: return self.oldDefault = defaultbutton if len(self['buttons']) > 0: if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) ###################################################################### ### File: PmwTimeFuncs.py # Functions for dealing with dates and times.
def _getValidatorFunc(self, validator, index): # Search the extra and standard validator lists for the # given 'validator'. If 'validator' is an alias, then # continue the search using the alias. Make sure that # self-referencial aliases do not cause infinite loops. extraValidators = self['extravalidators'] traversedValidators = [] while 1: traversedValidators.append(validator) if extraValidators.has_key(validator): validator = extraValidators[validator][index] elif _standardValidators.has_key(validator): validator = _standardValidators[validator][index] else: return validator if validator in traversedValidators: return validator
def realvalidator(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: return ERROR index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] try: string.atof(text) return OK except ValueError: # Check if the string could be made valid by appending a digit # eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-'). if len(text) == 0: return PARTIAL if text[-1] in string.digits: return ERROR try: string.atof(text + '0') return PARTIAL except ValueError: return ERROR
def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ parentName = self._menuInfo[menuName][0] del self._menuInfo[menuName] if parentName is None: parentMenu = self._menu else: parentMenu = self.component(parentName) menu = self.component(menuName) menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName)
def selectpage(self, page): pageName = self._pageNames[self.index(page)] oldTopPage = self.getcurselection() if pageName != oldTopPage: self._pending['topPage'] = pageName if oldTopPage == self._topPageName: self._hull.delete(self._topPageItem) cmd = self['lowercommand'] if cmd is not None: cmd(oldTopPage) self._raiseNewTop(pageName) self._layout() # Set focus to the tab of new top page: if self._withTabs and self['arrownavigation']: self._pageAttrs[pageName]['tabbutton'].focus_set()
def index(self, index): listLength = len(self._itemList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'OptionMenu has no items' else: if index is SELECT: if listLength > 0: index = self.getcurselection() else: raise ValueError, 'OptionMenu has no items' if index in self._itemList: return self._itemList.index(index) raise ValueError, \ 'bad index "%s": must be a ' \ 'name, a number, END or SELECT' % (index,)
def selectitem(self, index, setentry=1): if isinstance(index, basestring): text = index items = self._list.get(0, 'end') if text in items: index = list(items).index(text) else: raise IndexError, 'index "%s" not found' % text elif setentry: text = self._list.get(0, 'end')[index] self._list.select_clear(0, 'end') self._list.select_set(index, index) self._list.activate(index) self.see(index) if setentry: self._entryfield.setentry(text) # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid.
def _addHistory(self): input = self._entryWidget.get() if input != '': index = None if self['unique']: # If item is already in list, select it and return. items = self._list.get(0, 'end') if input in items: index = list(items).index(input) if index is None: index = self._list.index('end') self._list.insert('end', input) self.selectitem(index) if self['autoclear']: self._entryWidget.delete(0, 'end') # Execute the selectioncommand on the new entry. self._selectCmd()
def _next(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = 0 else: index = string.atoi(cursels[0]) if index == size - 1: index = 0 else: index = index + 1 self.selectitem(index)
def _forceCount(self, factor): if not self.valid(): self.bell() return text = self._counterEntry.get() try: value = apply(self._counterCommand, (text, factor, self['increment']), self._counterArgs) except ValueError: self.bell() return previousICursor = self._counterEntry.index('insert') if self._counterEntry.setentry(value) == OK: self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor)
def _changeDate(value, factor, increment, format = 'ymd', separator = '/', yyyy = 0): jdn = datestringtojdn(value, format, separator) + factor * increment y, m, d = jdntoymd(jdn) result = '' for index in range(3): if index > 0: result = result + separator f = format[index] if f == 'y': if yyyy: result = result + '%02d' % y else: result = result + '%02d' % (y % 100) elif f == 'm': result = result + '%02d' % m elif f == 'd': result = result + '%02d' % d return result
def main(): options = '' i = 1 while i < len(sys.argv) and sys.argv[i][:1] == '-': options = options + sys.argv[i] + ' ' i = i+1 args = sys.argv[i:] if not args: args = [''] for arg in args: if '@' in arg: at = string.index(arg, '@') host = arg[at+1:] arg = arg[:at] else: host = '' finger(host, options + arg) # Call the main function. #
def mirror_string(string): space = ' ' previous_index = None space_index = None while True: try: space_index = string.index(space, 0 if previous_index is None else previous_index + 1) if previous_index is None: string = "{0} {1}".format(string[:space_index][::-1], string[space_index + 1:]) else: string = "{0} {1} {2}".format(string[:previous_index], string[previous_index + 1: space_index][::-1], string[space_index + 1:]) previous_index = space_index except ValueError: break if space_index: string = "{0} {1}".format(string[:space_index], string[space_index + 1:][::-1]) else: string = string[::-1] return string
def _load_encoding(self): # map character code to bitmap index encoding = [None] * 256 fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS) firstCol, lastCol = i16(fp.read(2)), i16(fp.read(2)) firstRow, lastRow = i16(fp.read(2)), i16(fp.read(2)) default = i16(fp.read(2)) nencoding = (lastCol - firstCol + 1) * (lastRow - firstRow + 1) for i in range(nencoding): encodingOffset = i16(fp.read(2)) if encodingOffset != 0xFFFF: try: encoding[i+firstCol] = encodingOffset except IndexError: break # only load ISO-8859-1 glyphs return encoding
def _testKeys(self): """Verify that index lookup can find each word in the index file.""" print "Testing: ", self file = open(self.indexFile.file.name, _FILE_OPEN_MODE) counter = 0 while 1: line = file.readline() if line == '': break if line[0] != ' ': key = string.replace(line[:string.find(line, ' ')], '_', ' ') if (counter % 1000) == 0: print "%s..." % (key,), import sys sys.stdout.flush() counter = counter + 1 self[key] file.close() print "done."
def _index(key, sequence, testfn=None, keyfn=None): """Return the index of key within sequence, using testfn for comparison and transforming items of sequence by keyfn first. >>> _index('e', 'hello') 1 >>> _index('E', 'hello', testfn=_equalsIgnoreCase) 1 >>> _index('x', 'hello') """ index = 0 for element in sequence: value = element if keyfn: value = keyfn(value) if (not testfn and value == key) or (testfn and testfn(value, key)): return index index = index + 1 return None
def parseGenoFile(genoFile, names = None, includePositions = False, splitPhased=False, ploidy=None, headerLine = None): #get file headers headers = genoFile.readline().split() allNames = headers[2:] if names is None: names = allNames if splitPhased: if ploidy is None: ploidy = [2]*len(allNames) ploidyDict = dict(zip(allNames, ploidy)) #if splitting phased, we need to split names too allNames = [n + "_" + letter for n in allNames for letter in string.ascii_uppercase[:ploidyDict[n]]] names = [n + "_" + letter for n in names for letter in string.ascii_uppercase[:ploidyDict[n]]] #indices of samples nameIndices = dict(zip(names, [allNames.index(name) for name in names])) # records file column for each name #initialise an empty window window = GenoWindow(names = names) for line in iter(genoFile.readline,''): site = parseGenoLine(line,splitPhased) window.addSite(GTs=[site.GTs[nameIndices[name]] for name in names], position=site.position, ignorePosition= not includePositions) return window ########################################################################################################## #functions to make and parse alignment strings in fasta or phylip format
def material(self, mat, toName): """ Convert material to name/number :param mat: :param toName: :return: """ lst = self.materialList(0, False, True) if toName: mat -= 1 # 1 based if mat < 0 or mat >= len(lst): if mat != -1: # Accept -1 == 0 index raise Exception("Invalid material index requested idx=%d" % (mat + 1)) return "" return lst[mat] else: try: return lst.index(mat) + 1 except Exception: return 0
def region(self, reg, toName): """ Convert region to name/number :param reg: :param toName: :return: """ # Regions removing continuation cards regions = [x for x in self.cardsSorted("REGION") if x.name() != "&"] if len(regions) == 0: return None if toName: if reg <= 0 or reg > len(regions): return "" return regions[reg - 1].sdum() else: try: return [x.what(0) for x in regions].index(reg) + 1 except Exception: return 0
def set_positionLineOffset(self, line, offset): text = self.get_chars(0, -1) pos = 0 for l in xrange(line - 1): pos = string.index(text, '\n', pos) + 1 pos = pos + offset - 1 self.set_position(pos)
def __init__(self, ctime, atime, mtime, filesize, allocsize, attribs, shortname, longname): self.__ctime = ctime self.__atime = atime self.__mtime = mtime self.__filesize = filesize self.__allocsize = allocsize self.__attribs = attribs try: self.__shortname = shortname[:string.index(shortname, '\0')] except ValueError: self.__shortname = shortname try: self.__longname = longname[:string.index(longname, '\0')] except ValueError: self.__longname = longname
def _compile(self, reverse, fuzzy): index = self.info.named_lists_used[self.set_key] items = self.info.kwargs[self.name] case_flags = self.case_flags if not items: return [] encoding = self.info.flags & _ALL_ENCODINGS fold_flags = encoding | case_flags if fuzzy: choices = [self._folded(fold_flags, i) for i in items] # Sort from longest to shortest. choices.sort(key=lambda s: (-len(s), s)) branches = [] for string in choices: branches.append(Sequence([Character(c, case_flags=case_flags) for c in string])) if len(branches) > 1: branch = Branch(branches) else: branch = branches[0] branch = branch.optimise(self.info, reverse).pack_characters(self.info) return branch.compile(reverse, fuzzy) else: min_len = min(len(i) for i in items) max_len = max(len(self._folded(fold_flags, i)) for i in items) return [(self._opcode[case_flags, reverse], index, min_len, max_len)]
def get(self): string = self.string pos = self.pos try: if self.ignore_space: while True: if string[pos].isspace(): # Skip over the whitespace. pos += 1 elif string[pos] == "#": # Skip over the comment to the end of the line. pos = string.index("\n", pos) else: break ch = string[pos] self.pos = pos + 1 return ch except IndexError: # We've reached the end of the string. self.pos = pos return string[ : 0] except ValueError: # The comment extended to the end of the string. self.pos = len(string) return string[ : 0]
def get_many(self, count=1): string = self.string pos = self.pos try: if self.ignore_space: substring = [] while len(substring) < count: while True: if string[pos].isspace(): # Skip over the whitespace. pos += 1 elif string[pos] == "#": # Skip over the comment to the end of the line. pos = string.index("\n", pos) else: break substring.append(string[pos]) pos += 1 substring = "".join(substring) else: substring = string[pos : pos + count] pos += len(substring) self.pos = pos return substring except IndexError: # We've reached the end of the string. self.pos = len(string) return "".join(substring) except ValueError: # The comment extended to the end of the string. self.pos = len(string) return "".join(substring)
def match(self, substring): string = self.string pos = self.pos if self.ignore_space: try: for c in substring: while True: if string[pos].isspace(): # Skip over the whitespace. pos += 1 elif string[pos] == "#": # Skip over the comment to the end of the line. pos = string.index("\n", pos) else: break if string[pos] != c: return False pos += 1 self.pos = pos return True except IndexError: # We've reached the end of the string. return False except ValueError: # The comment extended to the end of the string. return False else: if not string.startswith(substring, pos): return False self.pos = pos + len(substring) return True
def __unique(): global __counter __counter = __counter + 1 return str(__counter) # Function body to resolve a forwarding given the target method name and the # index of the resolution function. The resulting lambda requires only self, # but will forward any other parameters. The target instance is identified # by invoking the resolution function.
def initialiseoptions(self, dummy = None): self._initialiseoptions_counter = self._initialiseoptions_counter - 1 if self._initialiseoptions_counter == 0: unusedOptions = [] keywords = self._constructorKeywords for name in keywords.keys(): used = keywords[name][1] if not used: # This keyword argument has not been used. If it # does not refer to a dynamic group, mark it as # unused. index = string.find(name, '_') if index < 0 or name[:index] not in self._dynamicGroups: unusedOptions.append(name) if len(unusedOptions) > 0: if len(unusedOptions) == 1: text = 'Unknown option "' else: text = 'Unknown options "' raise KeyError, text + string.join(unusedOptions, ', ') + \ '" for ' + self.__class__.__name__ # Call the configuration callback function for every option. FUNCTION = _OPT_FUNCTION for info in self._optionInfo.values(): func = info[FUNCTION] if func is not None and func is not INITOPT: func() #====================================================================== # Method used to configure the megawidget.
def component(self, name): # Return a component widget of the megawidget given the # component's name # This allows the user of a megawidget to access and configure # widget components directly. # Find the main component and any subcomponents index = string.find(name, '_') if index < 0: component = name remainingComponents = None else: component = name[:index] remainingComponents = name[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: if remainingComponents is None: remainingComponents = subComponent else: remainingComponents = subComponent + '_' \ + remainingComponents widget = self.__componentInfo[component][0] if remainingComponents is None: return widget else: return widget.component(remainingComponents)
def cget(self, option): # Get current configuration setting. # Return the value of an option, for example myWidget['font']. if self._optionInfo.has_key(option): return self._optionInfo[option][_OPT_VALUE] else: index = string.find(option, '_') if index >= 0: component = option[:index] componentOption = option[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' + componentOption # Expand option string to write on error option = component + '_' + componentOption if self.__componentInfo.has_key(component): # Call cget on the component. componentCget = self.__componentInfo[component][3] return componentCget(componentOption) else: # If this is a group name, call cget for one of # the components in the group. for info in self.__componentInfo.values(): if info[4] == component: componentCget = info[3] return componentCget(componentOption) raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__
def popgrab(window): # Return the grab to the next window in the grab stack, if any. # If this window is not at the top of the grab stack, then it has # just been deleted by the window manager or deactivated by a # timer. Call the deactivate method for the modal dialog above # this one on the stack. if _grabStack[-1]['grabWindow'] != window: for index in range(len(_grabStack)): if _grabStack[index]['grabWindow'] == window: _grabStack[index + 1]['deactivateFunction']() break grabInfo = _grabStack[-1] del _grabStack[-1] topWidget = grabInfo['grabWindow'] prevFocus = grabInfo['previousFocus'] globalMode = grabInfo['globalMode'] if globalMode != 'nograb': topWidget.grab_release() if len(_grabStack) > 0: _grabtop() if prevFocus != '': try: topWidget.tk.call('focus', prevFocus) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to root window. Tkinter._default_root.focus_set() else: # Make sure that focus does not remain on the released widget. if len(_grabStack) > 0: topWidget = _grabStack[-1]['grabWindow'] topWidget.focus_set() else: Tkinter._default_root.focus_set()
def invoke(self, index = DEFAULT): return self._buttonBox.invoke(index)
def _invokeDefault(self, event): try: self._buttonBox.index(DEFAULT) except ValueError: return self._buttonBox.invoke()
def _buttons(self): buttons = self['buttons'] if type(buttons) != types.TupleType and type(buttons) != types.ListType: raise ValueError, \ 'bad buttons option "%s": should be a tuple' % str(buttons) if self.oldButtons == buttons: return self.oldButtons = buttons for index in range(self._buttonBox.numbuttons()): self._buttonBox.delete(0) for name in buttons: self._buttonBox.add(name, command=lambda self=self, name=name: self._doCommand(name)) if len(buttons) > 0: defaultbutton = self['defaultbutton'] if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) self._buttonBox.alignbuttons()
def stringtoreal(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: raise ValueError, 'invalid value: ' + text index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] return string.atof(text) ###################################################################### ### File: PmwBalloon.py
def tagunbind(self, widget, tagOrItem): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(tagOrItem): (enterId, motionId, leaveId, buttonId) = \ widget._Pmw_BalloonBindIds[tagOrItem] widget.tag_unbind(tagOrItem, '<Enter>', enterId) widget.tag_unbind(tagOrItem, '<Motion>', motionId) widget.tag_unbind(tagOrItem, '<Leave>', leaveId) widget.tag_unbind(tagOrItem, '<ButtonPress>', buttonId) del widget._Pmw_BalloonBindIds[tagOrItem] if self._currentTrigger is None: # The balloon is not currently being displayed. return if len(self._currentTrigger) == 1: # The current trigger is a widget. return if len(self._currentTrigger) == 2: # The current trigger is a canvas item. (triggerWidget, triggerItem) = self._currentTrigger if triggerWidget == widget and triggerItem == tagOrItem: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None else: # The current trigger is a text item. (triggerWidget, x, y) = self._currentTrigger if triggerWidget == widget: currentPos = widget.index('@%d,%d' % (x, y)) currentTags = widget.tag_names(currentPos) if tagOrItem in currentTags: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None