我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.find()。
def get_build_version(): """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ prefix = "MSC v." i = string.find(sys.version, prefix) if i == -1: return 6 i = i + len(prefix) s, rest = sys.version[i:].split(" ", 1) majorVersion = int(s[:-2]) - 6 minorVersion = int(s[2:3]) / 10.0 # I don't think paths are affected by minor version in version 6 if majorVersion == 6: minorVersion = 0 if majorVersion >= 6: return majorVersion + minorVersion # else we don't know what version of the compiler this is return None
def find_library_file (self, dirs, lib, debug=0): # Prefer a debugging library if found (and requested), but deal # with it if we don't have one. if debug: try_names = [lib + "_d", lib] else: try_names = [lib] for dir in dirs: for name in try_names: libfile = os.path.join(dir, self.library_filename (name)) if os.path.exists(libfile): return libfile else: # Oops, didn't find it in *any* of 'dirs' return None # find_library_file () # Helper methods for using the MSVC registry settings
def find_exe(self, exe): """Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the original program name, 'exe'. """ for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn # didn't find it; try existing path for p in string.split(os.environ['Path'],';'): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn return exe
def get_msvcr(): """Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later. """ msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = sys.version[msc_pos+6:msc_pos+10] if msc_ver == '1300': # MSVC 7.0 return ['msvcr70'] elif msc_ver == '1310': # MSVC 7.1 return ['msvcr71'] elif msc_ver == '1400': # VS2005 / MSVC 8.0 return ['msvcr80'] elif msc_ver == '1500': # VS2008 / MSVC 9.0 return ['msvcr90'] else: raise ValueError("Unknown MS Compiler version %s " % msc_ver)
def replacestrs(filename): "replace a certain type of string occurances in all files in a directory" files = glob.glob(filename) #print 'files in files:', files stext = '-d0' rtext = '-r0' for line in fileinput.input(files,inplace=1): lineno = 0 lineno = string.find(line, stext) if lineno >0: line =line.replace(stext, rtext) sys.stdout.write(line)
def stripAxisCode(fileName): """copy lines from in file to out file up to first occurance of the string 'org.apache.axis', then just write closing brace. hasAxisCode detects of the file was already processed such that this is an idempotent operation. """ hasAxisCode = False fin = open(fileName, 'r') outName = ''.join([fileName, '.tmp']) fout = open(outName, 'wr') for line in fin: if (string.find(line, 'org.apache.axis') != -1 and string.find(line, 'extends') == -1 and string.find(line, 'implements') == -1): hasAxisCode = True break else: fout.write(line) fin.close() if hasAxisCode: fout.write("}\n") fout.close shutil.move(outName, fileName)
def strFile(p, f, caseSensitive=True): """Find whether string p occurs in a read()able object f @rtype: C{bool} """ buf = "" buf_len = max(len(p), 2**2**2**2) if not caseSensitive: p = p.lower() while 1: r = f.read(buf_len-len(p)) if not caseSensitive: r = r.lower() bytes_read = len(r) if bytes_read == 0: return False l = len(buf)+bytes_read-buf_len if l <= 0: buf = buf + r else: buf = buf[l:] + r if buf.find(p) != -1: return True
def stripEscapes(self, string): """ Remove all ANSI color escapes from the given string. """ result = '' show = 1 i = 0 L = len(string) while i < L: if show == 0 and string[i] in _sets: show = 1 elif show: n = string.find('\x1B', i) if n == -1: return result + string[i:] else: result = result + string[i:n] i = n show = 0 i = i + 1 return result
def _findVariable(self, variableName): # TODO Kann man hier nicht _findReference benutzen? variableName = variableName.lower() if not variableName: return None elif find(variableName, '%') < 0: if self.__subroutine.hasVariable(variableName): return self.__subroutine.getVariable(variableName) for reference in (self._typeArgumentReferences + self._globalsReferences): expression = reference.getExpression().lower() if expression == variableName: return reference.getLevelNVariable() elif expression.startswith(variableName + '%'): return reference.getVariable(variableName.count('%')) return None
def lhcidrs(lip, hip): """Convert a range from lowip to highip to a set of address/mask values.""" r = [] while lip <= hip: # algorithm: # try successively smaller length blocks starting at lip # until we find one that fits within lip,hip. add it to # the list, set lip to one plus its end, keep going. # we must insure that the chosen mask has lip as its proper # lower end, and doesn't go lower. lb = ffs(lip) if lb == -1: lb = 32 while lb >= 0: (lt, ht) = cidrrange((lip, (32-lb))) if lt == lip and ht <= hip: break lb = lb - 1 if lb < 0: raise ArithmeticError, "something horribly wrong" r.append((lip, (32-lb))) lip = ht+1 return r # This class handles network blocks.
def cidrstrerr(str): """Check an IP address or CIDR netblock for validity. Returns None if it is and otherwise an error string.""" if not cvalid.match(str): return 'Not a syntatically valid IP address or netblock' rng = 32 pos = string.find(str, '/') ips = str if not pos == -1: rng = string.atoi(ips[pos+1:]) ips = str[:pos] if rng < 0 or rng > 32: return 'CIDR length out of range' n = string.split(ips, '.') for i in n: ip = string.atoi(i) if (ip < 0 or ip > 255): return 'an IP octet is out of range' # could check to see if it is 'proper', but. return None
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 Get_Line_Pairs(self,str): line=0 line_pairs=dxflinepairsClass([]) #Start bei der ersten SECTION while (find(str[line],"SECTION")<0): line+=1 line-=1 #Durchlauf bis zum Ende falls kein Fehler auftritt. Ansonsten abbruch am Fehler try: while line < len(str): line_pairs.line_pair.append(dxflinepairClass(int(strip(str[line])),strip(str[line+1]))) line+=2 except: showwarning("Warning reading linepairs",("Failure reading line stopped at line %0.0f.\n Please check/correct line in dxf file" %(line))) self.textbox.prt(("\n!Warning! Failure reading lines stopped at line %0.0f.\n Please check/correct line in dxf file\n " %(line))) line_pairs.nrs=len(line_pairs.line_pair) return line_pairs #Suchen der Sectionen innerhalb des DXF-Files ntig um Blcke zu erkennen.
def find_matching_rule(self, frame): #initialze rule to none to return if no matching rules are found rule = None #check if frame matches exact rule if(frame.strFrame in self.dictExactFrame): rule = self.dictExactFrame[frame.strFrame]; #check if frame matches rule with an exact module if (rule is None and frame.strModule in self.dictExactModule): ruleIdx = self.__find_indexof_first_match(frame.strRoutine, [rule.strRoutine for rule in self.dictExactModule[frame.strModule]]) if (ruleIdx >= 0): rule = self.dictExactModule[frame.strModule][ruleIdx] #check if frame matches rule with an exact routine if (rule is None and frame.strRoutine in self.dictExactRoutine): ruleIdx = self.__find_indexof_first_match(frame.strRoutine, [rule.strModule for rule in self.dictExactRoutine[frame.strRoutine]]) if (ruleIdx >= 0): rule = self.dictExactModule[frame.strModule][ruleIdx] #check if frame matches wildcard rule ruleIdx = self.__find_indexof_first_match(frame.strRoutine, [rule.strFrame for rule in self.lstWildRules]) if (ruleIdx >= 0): rule = self.lstWildRules[ruleIdx] return rule ## private - finds the index of the first wildcard expression matching the specified string ## str - string to find a matching expression ## lstExpr - a list of expression to evaluate against the specified string
def CopyAndBag(self): #### Checking the Footage and then Copy for i in range (0,len(self.rdir)): if ('%' in self.tmpF[i]): ind = string.find(self.tmpF[i],'%',0,len(self.tmpF[i])) fname = self.tmpF[i][0:ind] enum = self.tmpF[i][ind:-4] ext = self.tmpF[i][-4:] seq = [] for file in os.listdir(self.tmpD[i]): if fnmatch.fnmatch(file, fname + '*'): for j in range (self.stF[i],self.edF[i]): if fnmatch.fnmatch(file, '*'+str(j) + ext): filelist = list(file) filelist1 = string.join(filelist,"") seq.append(filelist1) for elm in seq: shutil.copy(self.tmpD[i] + elm, self.rdir[i] +elm) else: shutil.copy(self.tmpDir[i], self.rdir[i]+ self.tmpF[i]) self.zipArchive()
def get_identifier_value(str, tag_uses): underscore_pos = string.find(str, "_") result = -1 if (underscore_pos > 0): tag_str = str[0:underscore_pos] id_str = str[underscore_pos + 1:len(str)] (tag_type, id_no) = get_id_value(tag_str,id_str,tag_uses) if (tag_type > 0): if (id_no < 0): print "Error: Unable to find object:" + str else: result = id_no | (tag_type << op_num_value_bits) else: print "Error: Unrecognized tag:" +tag_str + "in object:" + str else: print "Error: Invalid object:" +str + ".Variables should start with $ sign and references should start with a tag" return result
def parseArgs(args): """Given a list of strings, produces a list where those strings have been parsed (where possible) as floats or integers.""" parsed = [] for arg in args: print(arg) arg = arg.strip() interpretation = None try: interpretation = float(arg) if string.find(arg, ".") == -1: interpretation = int(interpretation) except: # Oh - it was a string. interpretation = arg pass parsed.append(interpretation) return parsed
def main(): if len(sys.argv) < 3: print "usage: rpython host command" sys.exit(2) host = sys.argv[1] port = PORT i = string.find(host, ':') if i >= 0: port = string.atoi(port[i+1:]) host = host[:i] command = string.join(sys.argv[2:]) s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(command) s.shutdown(1) reply = '' while 1: data = s.recv(BUFSIZE) if not data: break reply = reply + data print reply,
def __getfilesystemencoding(): ''' Note: there's a copy of this method in _pydev_filesystem_encoding.py ''' try: ret = sys.getfilesystemencoding() if not ret: raise RuntimeError('Unable to get encoding.') return ret except: try: # Handle Jython from java.lang import System # @UnresolvedImport env = System.getProperty("os.name").lower() if env.find('win') != -1: return 'ISO-8859-1' # mbcs does not work on Jython, so, use a (hopefully) suitable replacement return 'utf-8' except: pass # Only available from 2.3 onwards. if sys.platform == 'win32': return 'mbcs' return 'utf-8'
def getControllers(): """ Query the controllers available, and return this in a list. Returns: List with available 3ware controllers (list). """ T = TRACE() cmd = "sudo /usr/local/sbin/tw_cli info" stat, out = commands.getstatusoutput(cmd) if (stat): raise Exception, "Error invoking 3ware Command Line Tool: " + str(out) contList = [] for line in out.split("\n"): line = line.strip() if (line): if (line.find("Controller") == 0): # "Controller 1: 8506-4LP (4)" contNo = line.split(" ")[1].split(":")[0] contList.append(contNo) elif (line[0] == "c"): contNo = int(line.split(" ")[0][1:]) contList.append(contNo) contList.sort() return contList
def _test_MultipartWriter(self, onlyDirs): contents = self._createMIMEMessage(onlyDirs) self.assertTrue(contents, "No contents found") self.assertTrue(contents.find("MIME-Version: 1.0") != -1, "Content is not a MIME message") self.assertTrue(contents.find("Content-Type: multipart/mixed") != -1, "Content is not a multipart message") # There should be a different boundaries declaration for each directory # since each will result in a multipart message nBoundaries = self._findOccurences(contents, 'boundary="') self.assertEqual(nBoundaries, len(self.mydirs), "Didn't find all boundary definitions that were expected") # There should be a "filename" declaration for each file # since each will result in a MIME message inside one of the multiparts if not onlyDirs: nFilenames = self._findOccurences(contents, 'filename="') self.assertEquals(nFilenames, len(self.myfiles), "Didn't find all filename definitions that were expected")
def index(tagname): """Return the name of the submodule that tagname is defined in, as well as a list of modules and keys in which this tagname is used.""" mods = glob.glob1(__path__[0], '*.py') keys = [] usedin = {} for m in mods: if m[:2] == '__': continue modname = __name__ + '.' + m[:-3] path = string.split(modname, '.') module = __import__(modname) # find the deepest submodule for modname in path[1:]: module = getattr(module, modname) if hasattr(module, 'content'): c = module.content for k in c.keys(): if k == tagname: keys.append(m) for item in c[k]: if string.find(item, tagname) != -1: usedin[(m, k)] = 1 return keys, usedin.keys()
def get_msvcr(): """Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later. """ msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = sys.version[msc_pos+6:msc_pos+10] if msc_ver == '1300': # MSVC 7.0 return ['msvcr70'] elif msc_ver == '1310': # MSVC 7.1 return ['msvcr71'] elif msc_ver == '1400': # VS2005 / MSVC 8.0 return ['msvcr80'] elif msc_ver == '1500': # VS2008 / MSVC 9.0 return ['msvcr90'] elif msc_ver == '1600': # VS2010 / MSVC 10.0 return ['msvcr100'] else: raise ValueError("Unknown MS Compiler version %s " % msc_ver)
def _readString(data): """Reads the next (null-terminated) block of data """ length = string.find(data,"\0") nextData = int(math.ceil((length+1) / 4.0) * 4) return (data[0:length], data[nextData:])
def get_build_architecture(): """Return the processor architecture. Possible results are "Intel", "Itanium", or "AMD64". """ prefix = " bit (" i = string.find(sys.version, prefix) if i == -1: return "Intel" j = string.find(sys.version, ")", i) return sys.version[i+len(prefix):j]
def find_library_file(self, dirs, lib, debug=0): shortlib = '%s.lib' % lib longlib = 'lib%s.lib' % lib # this form very rare # get EMX's default library directory search path try: emx_dirs = os.environ['LIBRARY_PATH'].split(';') except KeyError: emx_dirs = [] for dir in dirs + emx_dirs: shortlibp = os.path.join(dir, shortlib) longlibp = os.path.join(dir, longlib) if os.path.exists(shortlibp): return shortlibp elif os.path.exists(longlibp): return longlibp # Oops, didn't find it in *any* of 'dirs' return None # class EMXCCompiler # Because these compilers aren't configured in Python's pyconfig.h file by # default, we should at least warn the user if he is using a unmodified # version.