我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用string.strip()。
def _format_changelog(self, changelog): """Format the changelog correctly and convert it to a list of strings """ if not changelog: return changelog new_changelog = [] for line in string.split(string.strip(changelog), '\n'): line = string.strip(line) if line[0] == '*': new_changelog.extend(['', line]) elif line[0] == '-': new_changelog.append(line) else: new_changelog.append(' ' + line) # strip trailing newline inserted by first changelog entry if not new_changelog[0]: del new_changelog[0] return new_changelog # _format_changelog() # class bdist_rpm
def help(self, request): if type(request) is type(''): request = request.strip() if request == 'help': self.intro() elif request == 'keywords': self.listkeywords() elif request == 'symbols': self.listsymbols() elif request == 'topics': self.listtopics() elif request == 'modules': self.listmodules() elif request[:8] == 'modules ': self.listmodules(split(request)[1]) elif request in self.symbols: self.showsymbol(request) elif request in self.keywords: self.showtopic(request) elif request in self.topics: self.showtopic(request) elif request: doc(request, 'Help on %s:') elif isinstance(request, Helper): self() else: doc(request, 'Help on %s:') self.output.write('\n')
def __SkipRubish(self, aFilePathList): """ Edit this method to select the private file that will not be backed up. """ myFilteredList = [] for myFilePath in aFilePathList: myLowerFilePath = string.lower(string.strip(myFilePath)) if myLowerFilePath[-4:]=='.obj': continue if myLowerFilePath[-5:]=='.class': continue if myLowerFilePath[-1:]=='~': continue myFilteredList.append(myFilePath) return myFilteredList
def printexpr(expr_string): """ printexpr(expr) - print the value of the expression, along with linenumber and filename. """ stack = extract_stack ( )[-2:][0] actualCall = stack[3] left = string.find ( actualCall, '(' ) right = string.rfind ( actualCall, ')' ) caller_globals,caller_locals = _caller_symbols() expr = eval(expr_string,caller_globals,caller_locals) varType = type( expr ) stderr.write("%s:%d> %s == %s (%s)\n" % ( stack[0], stack[1], string.strip( actualCall[left+1:right] )[1:-1], repr(expr), str(varType)[7:-2]))
def _ParseWhois_Generic(self, fields): for field in fields: regex = "%s: *(.+)" % field['page_field'] #print regex if field['rec_field'] == "servers": self.servers = [] servers = re.findall(regex, self.page) for server in servers: try: server = string.strip(server) ip = socket.gethostbyname(server) except: ip = "?" self.servers.append((server, ip)) else: m = re.search(regex, self.page) #if m: print m.group(1) if m: setattr(self, field['rec_field'], string.strip(m.group(1)))
def source_synopsis(file): line = file.readline() while line[:1] == '#' or not strip(line): line = file.readline() if not line: break line = strip(line) if line[:4] == 'r"""': line = line[1:] if line[:3] == '"""': line = line[3:] if line[-1:] == '\\': line = line[:-1] while not strip(line): line = file.readline() if not line: break result = strip(split(line, '"""')[0]) else: result = None return result
def _syscmd_uname(option,default=''): """ Interface to the system's uname command. """ if sys.platform in ('dos','win32','win16','os2'): # XXX Others too ? return default try: f = os.popen('uname %s 2> %s' % (option, DEV_NULL)) except (AttributeError,os.error): return default output = string.strip(f.read()) rc = f.close() if not output or rc: return default else: return output
def write(self, group=0): """Write the whole thing to string""" t = [] if len(self.data) == 0: return None t.append('feature %s {' % self.type) for src, dst in self.data: if isinstance(src, (list, tuple)): if group: src = "[%s]" % string.join(src, ' ') else: src = string.join(src, ' ') if isinstance(dst, (list, tuple)): if group: dst = "[%s]" % string.join(dst, ' ') else: dst = string.join(dst, ' ') src = string.strip(src) dst = string.strip(dst) t.append("\tsub %s by %s;" % (src, dst)) t.append('}%s;' % self.type) return string.join(t, '\n')
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 load_from_triage_string(self, strTriage): splitOnEq = string.split(strTriage, "=") self.strFrame = splitOnEq[0] self.strFollowup = string.strip(splitOnEq[1]) splitOnBang = string.split(splitOnEq[0], "!") self.strModule = "*" self.strRoutine = "*" if(len(splitOnBang) > 1): self.strModule = splitOnBang[0] self.strRoutine = splitOnBang[1] elif self.strFrame.endswith("*"): self.strModule = self.strFrame.rstrip("*") elif self.strFrame.startswith("*"): self.strRoutine = self.strFrame.lstrip("*") else: self.strModule = self.strFrame self.bExactModule = "*" not in self.strModule self.bExactRoutine = "*" not in self.strRoutine self.bExactFrame = self.bExactModule and self.bExactRoutine
def _count_grids(self): self.num_grids = None test_grid = test_grid_id = None self.num_stars = 0 for line in rlines(open(self.index_filename, "rb")): if line.startswith("BaryonFileName") or \ line.startswith("ParticleFileName") or \ line.startswith("FileName "): test_grid = line.split("=")[-1].strip().rstrip() if line.startswith("NumberOfStarParticles"): self.num_stars = int(line.split("=")[-1]) if line.startswith("Grid "): if self.num_grids is None: self.num_grids = int(line.split("=")[-1]) test_grid_id = int(line.split("=")[-1]) if test_grid is not None: break self._guess_dataset_type(self.ds.dimensionality, test_grid, test_grid_id)
def load_variables(export_dir,variable_uses): variables = [] try: file = open(export_dir + "variables.txt","r") var_list = file.readlines() file.close() for v in var_list: vv = string.strip(v) if vv: variables.append(vv) except: print "variables.txt not found. Creating new variables.txt file" try: file = open(export_dir + "variable_uses.txt","r") var_list = file.readlines() file.close() for v in var_list: vv = string.strip(v) if vv: variable_uses.append(int(vv)) except: print "variable_uses.txt not found. Creating new variable_uses.txt file" return variables
def load_tag_uses(export_dir): tag_uses = [] for i in xrange(tags_end): sub_tag_uses = [] tag_uses.append(sub_tag_uses) try: file = open(export_dir + "tag_uses.txt","r") var_list = file.readlines() file.close() for v in var_list: vv = string.strip(v).split(';') if vv: for v2 in vv: vvv = v2.split(' ') if len(vvv) >= 3: ensure_tag_use(tag_uses,int(vvv[0]),int(vvv[1])) tag_uses[int(vvv[0])][int(vvv[1])] = int(vvv[2]) except: print "Creating new tag_uses.txt file..." return tag_uses
def help(self,note=''): self.print_header() if self.synopsis: print 'Synopsis:' # To remain backward compatible: try: synopsis = self.synopsis % self.name except (NameError, KeyError, TypeError): synopsis = self.synopsis % self.__dict__ print ' ' + synopsis print self.print_options() if self.version: print 'Version:' print ' %s' % self.version print if self.about: print string.strip(self.about % self.__dict__) print if note: print '-'*72 print 'Note:',note print
def browse_search(selector, host, port): while 1: print '----- SEARCH -----' print 'Selector:', repr(selector) print 'Host:', host, ' Port:', port print try: query = raw_input('Query [CR == up a level]: ') except EOFError: print break query = string.strip(query) if not query: break if '\t' in query: print 'Sorry, queries cannot contain tabs' continue browse_menu(selector + TAB + query, host, port) # "Browse" telnet-based information, i.e. open a telnet session
def page_leave(self): if self.lb_key_type.get_selected_index() == 0: self.frontend.choices.gpg_key_type = "RSA" self.frontend.choices.gpg_sub_key_type = "RSA" else: self.frontend.choices.gpg_key_type = "DSA" self.frontend.choices.gpg_sub_key_type = "ELG-E" self.frontend.choices.gpg_key_length = self.spn_key_length.get_value() self.frontend.choices.gpg_password = self.txt_password.get_text() self.frontend.choices.gpg_email = self.txt_email.get_text() self.frontend.choices.gpg_name = self.txt_name.get_text() self.frontend.choices.gpg_comment = self.txt_comment.get_text() # TODO: implement entropy generator self.frontend.choices.gpg_use_entropy_generator = True self.frontend.choices.disable_password = self.chk_disable_password.get_active() self.frontend.choices.gpg_key_expiry_date = datetime.datetime.strptime(string.strip(self.txt_key_expiry.get_text()), "%Y%m%d")
def validate(self): key_expiry_parsed = False try: key_expiry = datetime.datetime.strptime(string.strip(self.txt_key_expiry.get_text()), "%Y%m%d") key_expiry_parsed = True except Exception, ex: self.frontend.builder.root_widget.debugln("Didn't parse date: " + str(ex)) #TODO: alert user that their date doesn't parse pass if self.chk_disable_password.get_active() == True or \ (self.txt_password.get_text() == self.txt_password_confirm.get_text() and \ len(self.txt_password.get_text()) > 0 and \ key_expiry_parsed == True and \ key_expiry > datetime.datetime.now()): self.frontend.gui_set_sensitive("btn_forward", True) else: self.frontend.gui_set_sensitive("btn_forward", False)
def _configure_tool(self, toolname): """Check if the specified tool is already on the device, otherwise install it.""" # Retrieve install options tool = Constants.DEVICE_SETUP['TOOLS'][toolname] try: if tool['PACKAGES']: # Install via apt-get self.__install_package(toolname, tool) elif tool['LOCAL']: # Manual install self.__install_local(toolname, tool) elif tool['SETUP']: # Use list of commands self.__install_commands(toolname, tool) else: self.device.printer.debug('Installation method not provided for %s. Skipping' % toolname) except Exception as e: self.device.printer.warning('Error occurred during installation of tools: %s' % e.message.strip()) self.device.printer.warning('Trying to continue anyway...') # ================================================================================================================== # RUN # ==================================================================================================================
def parse_cited_numeric(self, citation_str): cited = [] citation_str = citation_str[1:-1] # Remove surrounding brackets [] cids = map(string.strip, citation_str.split(",")) for cid in cids : # Check if the range kind of e.g. [1-4] or not if cid.find('-')<0 : cited.append(cid) else : start, end = cid.split('-') cited_range = range(int(start.strip()), int(end.strip())+1) cited.extend(map(str, cited_range)) return cited
def _list_patches(patches, format_str=None): """Dump a list of patches to stdout.""" if format_str: format_field_re = re.compile("%{([a-z0-9_]+)}") def patch_field(matchobj): fieldname = matchobj.group(1) if fieldname == "_msgid_": # naive way to strip < and > from message-id val = string.strip(str(patch["msgid"]), "<>") else: val = str(patch[fieldname]) return val for patch in patches: print(format_field_re.sub(patch_field, format_str)) else: print("%-7s %-12s %s" % ("ID", "State", "Name")) print("%-7s %-12s %s" % ("--", "-----", "----")) for patch in patches: print("%-7d %-12s %s" % (patch['id'], patch['state'], patch['name']))
def decode(self, data): data = str(data) self.value = string.strip(data)
def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" lines = split(strip(doc), '\n') if len(lines) == 1: return lines[0], '' elif len(lines) >= 2 and not rstrip(lines[1]): return lines[0], join(lines[2:], '\n') return '', join(lines, '\n')
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)
def showtopic(self, topic, more_xrefs=''): try: import pydoc_data.topics except ImportError: self.output.write(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. ''') return target = self.topics.get(topic, self.keywords.get(topic)) if not target: self.output.write('no documentation found for %s\n' % repr(topic)) return if type(target) is type(''): return self.showtopic(target, more_xrefs) label, xrefs = target try: doc = pydoc_data.topics.topics[label] except KeyError: self.output.write('no documentation found for %s\n' % repr(topic)) return pager(strip(doc) + '\n') if more_xrefs: xrefs = (xrefs or '') + ' ' + more_xrefs if xrefs: import StringIO, formatter buffer = StringIO.StringIO() formatter.DumbWriter(buffer).send_flowing_data( 'Related help topics: ' + join(split(xrefs), ', ') + '\n') self.output.write('\n%s\n' % buffer.getvalue())
def _parse_release_file(firstline): # Default to empty 'version' and 'id' strings. Both defaults are used # when 'firstline' is empty. 'id' defaults to empty when an id can not # be deduced. version = '' id = '' # Parse the first line m = _lsb_release_version.match(firstline) if m is not None: # LSB format: "distro release x.x (codename)" return tuple(m.groups()) # Pre-LSB format: "distro x.x (codename)" m = _release_version.match(firstline) if m is not None: return tuple(m.groups()) # Unkown format... take the first two words l = string.split(string.strip(firstline)) if l: version = l[0] if len(l) > 1: id = l[1] return '', version, id
def _platform(*args): """ Helper to format the platform string in a filename compatible format e.g. "system-version-machine". """ # Format the platform string platform = string.join( map(string.strip, filter(len, args)), '-') # Cleanup some possible filename obstacles... replace = string.replace platform = replace(platform,' ','_') platform = replace(platform,'/','-') platform = replace(platform,'\\','-') platform = replace(platform,':','-') platform = replace(platform,';','-') platform = replace(platform,'"','-') platform = replace(platform,'(','-') platform = replace(platform,')','-') # No need to report 'unknown' information... platform = replace(platform,'unknown','') # Fold '--'s and remove trailing '-' while 1: cleaned = replace(platform,'--','-') if cleaned == platform: break platform = cleaned while platform[-1] == '-': platform = platform[:-1] return platform
def _syscmd_file(target,default=''): """ Interface to the system's file command. The function uses the -b option of the file command to have it ommit the filename in its output and if possible the -L option to have the command follow symlinks. It returns default in case the command should fail. """ if sys.platform in ('dos','win32','win16','os2'): # XXX Others too ? return default target = _follow_symlinks(target).replace('"', '\\"') try: f = os.popen('file "%s" 2> %s' % (target, DEV_NULL)) except (AttributeError,os.error): return default output = string.strip(f.read()) rc = f.close() if not output or rc: return default else: return output ### Information about the used architecture # Default values for architecture; non-empty strings override the # defaults given as parameters
def __init__(self, raw, out=sys.stdout, not_covered=[]): """ Store the source text. """ self.raw = string.strip(string.expandtabs(raw)) self.out = out self.not_covered = not_covered # not covered list of lines self.cover_flag = False # is there a <span> tag opened?
def __GetLocalViews(self): """ Return a list with all local view. """ import socket myClearCaseCommand = 'cleartool lsview' myHostName = string.lower(socket.gethostname()) myListLocalView = [] (mystdIn, myStdOut) = popen2.popen2(myClearCaseCommand) for myLine in mystdIn: myLowerLine = string.lower(myLine) myStartHostName = string.find(myLowerLine, myHostName) if myStartHostName != -1: myLocalView = myLine[2:myStartHostName-2] myListLocalView.append(string.strip(myLocalView)) self.__StartViews(myListLocalView) return myListLocalView return
def CharacterData(self,data): 'SAX character data event handler' if string.strip(data): data = data.encode() element = self.nodeStack[-1] element.cdata += data return
def chooseserver(self): try: toplevel = string.split(self.domain, ".")[-1] self.whoisserver=WhoisRecord.whoismap.get(toplevel) #print toplevel, "---", self.whoisserver if self.whoisserver==None: self.whoisserver=WhoisRecord.defaultserver return except: self.whoisserver=WhoisRecord.defaultserver return if toplevel in ('com', 'org', 'net'): tmp=self._whois() m = re.search("Whois Server:(.+)", tmp) if m: self.whoisserver=string.strip(m.group(1)) #print "server 2:", self.whoisserver return self.whoisserver='whois.networksolutions.com' tmp=self._whois() m=re.search("Whois Server:(.+)",tmp) if m: self.whoisserver=string.strip(m.group(1)) #print "server 1:", self.whoisserver return #print "server 3:", self.whoisserver
def _ParseGenericContact(self, contact_rec, contact, fields): for field in fields: m = re.search("%s *.*%s: *(.+)" % (contact, field['page_field']), self.page) if not m: continue setattr(contact_rec, field['rec_field'], string.strip(m.group(1)))
def getSubjectHash(self): """get the message's subject in a "normalized" form This currently means lowercasing and removing any reply or forward indicators. """ import re import string s = self.getSubject() if s == None: return '(no subject)' return re.sub(r'^(re|fwd?):\s*', '', string.strip(s.lower()))