当前位置: 首页>>代码示例>>Python>>正文


Python string.rstrip函数代码示例

本文整理汇总了Python中string.rstrip函数的典型用法代码示例。如果您正苦于以下问题:Python rstrip函数的具体用法?Python rstrip怎么用?Python rstrip使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了rstrip函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: constructmenuitemstring

  def constructmenuitemstring(self,items,keybindingsdict):
    def emptystring(num):
      if num<=0:
        return ""
      return " "+emptystring(num-1)
    
    if len(items)==1:
      return items[0]

    keykey=string.lstrip(string.rstrip(items[1]))
    if keykey not in keybindingsdict:
      ret = string.rstrip(items[0])
      commands[string.lstrip(ret)] = string.lstrip(items[1])
      return ret
    
    key=keybindingsdict[keykey]
    qualifier=""
    
    for item in key[1]:
      qualifier+=get_key_name(item)+" + "

      #print "items[0]",items[0],len(items[0]),qualifier
    stripped0 = string.rstrip(items[0])
    ret = stripped0 + emptystring(41-len(stripped0)) + qualifier + get_key_name(key[0][0])
    commands[string.lstrip(ret)] = string.lstrip(items[1])
    return ret
开发者ID:jakobvonrotz,项目名称:radium,代码行数:26,代码来源:menues.py

示例2: getLabel

    def getLabel(self, partition):
        label = None
        fd = self.openPartition(partition)

        # valid block sizes in reiserfs are 512 - 8192, powers of 2
        # we put 4096 first, since it's the default
        # reiserfs superblock occupies either the 2nd or 16th block
        for blksize in (4096, 512, 1024, 2048, 8192):
            for start in (blksize, (blksize*16)):
                try:
                    os.lseek(fd, start, 0)
                    # read 120 bytes to get s_magic and s_label
                    buf = os.read(fd, 120)

                    # see if this block is the superblock
                    # this reads reiserfs_super_block_v1.s_magic as defined
                    # in include/reiserfs_fs.h in the reiserfsprogs source
                    m = string.rstrip(buf[52:61], "\0x00")
                    if m == "ReIsErFs" or m == "ReIsEr2Fs" or m == "ReIsEr3Fs":
                        # this reads reiserfs_super_block.s_label as
                        # defined in include/reiserfs_fs.h
                        label = string.rstrip(buf[100:116], "\0x00")
                        os.close(fd)
                        return label
                except OSError, e:
                    # [Error 22] probably means we're trying to read an
                    # extended partition. 
                    e = "error reading reiserfs label on %s: %s" %(partition.getPath(), e)
                    raise YaliException, e
开发者ID:dhirajkhatiwada1,项目名称:uludag,代码行数:29,代码来源:filesystem.py

示例3: read

def read(category, disc_id, server_url=default_server, 
         user=default_user, host=hostname, client_name=name,
         client_version=version):

    url = "%s?cmd=cddb+read+%s+%s&hello=%s+%s+%s+%s&proto=%i" % \
          (server_url, category, disc_id, user, host, client_name,
           client_version, proto)

    response = urllib.urlopen(url)
    
    header = string.split(string.rstrip(response.readline()), ' ', 3)

    header[0] = string.atoi(header[0])
    if header[0] == 210 or header[0] == 417: # success or access denied
        reply = []

        for line in response.readlines():
            line = string.rstrip(line)

            if line == '.':
                break;

            line = string.replace(line, r'\t', "\t")
            line = string.replace(line, r'\n', "\n")
            line = string.replace(line, r'\\', "\\")

            reply.append(line)

        if header[0] == 210:                # success, parse the reply
            return [ header[0], parse_read_reply(reply) ]
        else:                                # access denied. :(
            return [ header[0], reply ]
    else:
        return [ header[0], None ]
开发者ID:KMNR,项目名称:KLAP-CDDBAdds,代码行数:34,代码来源:CDDB.py

示例4: main

def main():
    addr = {}

    if len(sys.argv) != 2:
        print "Usage: {0} ipaddress".format(sys.argv[0])
        sys.exit(1)

    ctx = getdns.context_create()
    addr["address_data"] = sys.argv[1]
    if string.find(sys.argv[1], ":") != -1:
        addr["address_type"] = "IPv6"
    elif string.find(sys.argv[1], ".") != 1:
        addr["address_type"] = "IPv4"
    else:
        print "{0}: undiscernable address type".format(sys.argv[1])
        sys.exit(1)
    results = getdns.hostname(ctx, address=addr)
    if results["status"] == getdns.GETDNS_RESPSTATUS_GOOD:
        print "Hostnames:"
        for responses in results["replies_tree"]:
            for ans in responses["answer"]:
                print string.rstrip(ans["rdata"]["ptrdname"], ".")

    if results["status"] == getdns.GETDNS_RESPSTATUS_NO_NAME:
        print "{0} not found".format(sys.argv[1])
开发者ID:saghul,项目名称:getdns-python-bindings,代码行数:25,代码来源:example_hostname.py

示例5: read

 def read( self, faFileHandler ):
     line = faFileHandler.readline()
     if line == "":
         self.header = None
         self.sequence = None
         return
     while line == "\n":
         line = faFileHandler.readline()
     if line[0] == '>':
         self.header = string.rstrip(line[1:])
     else:
         print "error, line is",string.rstrip(line)
         return
     line = " "
     seq = cStringIO.StringIO()
     while line:
         prev_pos = faFileHandler.tell()
         line = faFileHandler.readline()
         if line == "":
             break
         if line[0] == '>':
             faFileHandler.seek( prev_pos )
             break
         seq.write( string.rstrip(line) )
     self.sequence = seq.getvalue()
开发者ID:chungtseng,项目名称:HCPU_midterm,代码行数:25,代码来源:Bioseq.py

示例6: colorize

def colorize(line):
	orig_line = line
	try:
		time = get_first_bracket(line)
		line = remove_first_bracket(line)

		found = 0
		for log in log_color.keys():
			if string.find(line, log) >= 0:
				found = 1
				line = remove_first_bracket(line)
				line = string.strip(line)
				line = string.split(line, ' ',2) ## XXX: magic number 2
				line[filename] = GREEN + line[filename] + CLEAR
				line[message] = log_color[log] + line[message] + CLEAR
				break

		if not found:
			return string.rstrip(orig_line)

		if show_time:
			line.insert(0,time)
	except:
		return string.rstrip(orig_line)

	return string.join(line, ' ')
开发者ID:aragorn,项目名称:wisebot,代码行数:26,代码来源:colorlog.py

示例7: include

	def include(self, domain, initialstate, goalstate, plan, success, shouldIWrite=True):
		domain = string.rstrip(domain, '\n')
		initialstate = string.rstrip(initialstate, '\n')
		goalstate = string.rstrip(goalstate, '\n')
		#try:
		if shouldIWrite:
			try:
				#print 'PLAN: ', plan
				D = open('cache_D'+str(self.availableId)+'.py', 'w')
				D.write(domain)
				D.close()
				I = open('cache_I'+str(self.availableId)+'.xml', 'w')
				I.write(initialstate)
				I.close()
				G = open('cache_G'+str(self.availableId)+'.py', 'w')
				G.write(goalstate)
				G.close()
				P = open('cache_plan'+str(self.availableId)+'.agglp', 'w')
				if success: P.write(plan)
				else: P.write('fail')
				P.close()
			except:
				print 'Can\'t write cache'
				traceback.print_exc()
				sys.exit(-1)
		self.availableId += 1
		md = md5.new()
		md.update(domain+initialstate+goalstate)
		checksum = md.hexdigest()
		print 'Including planning context with checksum', checksum
		try:
			self.data[checksum].append((domain, initialstate, goalstate, plan, success))
		except:
			self.data[checksum] = []
			self.data[checksum].append((domain, initialstate, goalstate, plan, success))
开发者ID:ljmanso,项目名称:AGM,代码行数:35,代码来源:agglplanningcache.py

示例8: create_session

 def create_session(self, request, email, ssid, expiration):
   """
   Encrypt parameters, set valid in DB, set cookie on client
   """
   account = memcache_db.get_entity(email, "Accounts")
   if account != None:
     update_fields = {"cookieKey" : ssid}
     memcache_db.update_fields(email, "Accounts", update_fields)
   
     email_enc = encryption.des_encrypt_str(email)
     ssid_enc = encryption.des_encrypt_str(ssid)
     exp_enc = encryption.des_encrypt_str(expiration)
     
     import base64
     import string
     email_encoded = string.rstrip(base64.encodestring(email_enc), "\n")
     ssid_encoded = string.rstrip(base64.encodestring(ssid_enc), "\n")
     exp_encoded = string.rstrip(base64.encodestring(exp_enc), "\n")
 
     # the email will be set as the key so we can use it to look up in the DB
     request.response.headers.add_header("Set-Cookie", WEB_ADMIN_PARAMS.COOKIE_EMAIL_PARAM + "=" + email_encoded)
     request.response.headers.add_header("Set-Cookie", WEB_ADMIN_PARAMS.COOKIE_KEY_PARAM + "=" + ssid_encoded)
     request.response.headers.add_header("Set-Cookie", WEB_ADMIN_PARAMS.COOKIE_EXPIRATION + "=" + exp_encoded)
     
     """ Create a new session object and return it """
     self.email = email
     self.ssid = ssid
     self.expiration = expiration
     self.account = account
   
     return self
   else:
     return None
开发者ID:AkilDixon,项目名称:UserInfuser,代码行数:33,代码来源:session.py

示例9: get_sender

	def get_sender(self, ignore_header=""):
		"""
		Returns a tuple in the format (sender_name, sender_email). Some processing is
		done to treat X-Primary-Address/Resent-From/Reply-To/From. Headers in "ignore_header"
		are not checked.
		"""

		headers = ["X-Primary-Address", "Resent-From", "Reply-To", "From"];

		## Remove unwanted headers
		def fn_remove(x, y = ignore_header): return(x != y)
		headers = filter(fn_remove, headers)

		sender_name = ''
		sender_mail = ''

		for hdr in headers:
			(sender_name, sender_mail) = self.msg.getaddr(hdr)

			if sender_name == None: sender_name = ''
			if sender_mail == None: sender_mail = ''

			## Decode sender name and return if found
			if sender_mail:
				if sender_name:
                                       sender_name = decode_header(sender_name)
                                       sender_name = sender_name[0][0]
				break

		return(string.rstrip(sender_name), string.rstrip(sender_mail))
开发者ID:celer,项目名称:ask,代码行数:30,代码来源:askmessage.py

示例10: getallsubs

def getallsubs(content, language, search_string, season, episode):
    i = 0
    for matches in re.finditer(subtitle_pattern, content, re.IGNORECASE | re.DOTALL):
        i = i + 1
        title_found = unescape(string.rstrip(matches.group(2)))
        log( __name__ , title_found )
        log( __name__ , search_string )
        if string.find(string.lower(title_found),string.lower(search_string)) > -1:
            subtitle_id    = matches.group(1)
            year_found     = matches.group(3)
            season_episode_found = string.rstrip(matches.group(4))
            filename = title_found
            languageshort = toOpenSubtitles_two(language)
            match = re.match(subinfo_pattern, matches.group(5), re.IGNORECASE | re.DOTALL)
            if match:
                description = match.group(1)
                filename = filename + ' ' + description
            if len(season) > 0:
                season_episode = 'Sezona' + season + ' Epizoda' + episode
                if season_episode == season_episode_found:
                    subtitles_list.append({'rating': '0', 'sync': False, 'filename': filename, 'subtitle_id': subtitle_id, 'language_flag': 'flags/' + languageshort+ '.gif', 'language_name': language})
                    log( __name__ ,"%s Subtitles found: %s (id = %s)" % (debug_pretext, filename, subtitle_id))
            else:
                if len(season_episode_found) == 0:
                    subtitles_list.append({'rating': '0', 'sync': False, 'filename': filename, 'subtitle_id': subtitle_id, 'language_flag': 'flags/' + languageshort+ '.gif', 'language_name': language})
                    log( __name__ ,"%s Subtitles found: %s (id = %s)" % (debug_pretext, filename, subtitle_id))
开发者ID:gNuSoftWare,项目名称:script.xbmc.subtitles,代码行数:26,代码来源:service.py

示例11: on_afMoleculeAddPB_clicked

    def on_afMoleculeAddPB_clicked(self):

        molecule = str(self.afMoleculeLE.text())
        molecule = string.rstrip(molecule)
        rows = self.afTable.rowCount()
        if molecule == "":
            return

        # check if molecule with this name already exist               
        moleculeAlreadyExists = False
        for rowId in range(rows):
            name = str(self.afTable.item(rowId, 0).text())
            name = string.rstrip(name)
            if name == molecule:
                moleculeAlreadyExists = True
                break

        if moleculeAlreadyExists:
            QMessageBox.warning(self, "Molecule Name Already Exists",
                                "Molecule name already exist. Please choose different name", QMessageBox.Ok)
            return

        self.afTable.insertRow(rows)
        moleculeItem = QTableWidgetItem(molecule)
        self.afTable.setItem(rows, 0, moleculeItem)

        # reset molecule entry line
        self.afMoleculeLE.setText("")
        return
开发者ID:CompuCell3D,项目名称:CompuCell3D,代码行数:29,代码来源:adhesionflexdlg.py

示例12: reformat_paragraph

def reformat_paragraph(data, limit=70):
    lines = string.split(data, "\n")
    i = 0
    n = len(lines)
    while i < n and is_all_white(lines[i]):
        i = i+1
    if i >= n:
        return data
    indent1 = get_indent(lines[i])
    if i+1 < n and not is_all_white(lines[i+1]):
        indent2 = get_indent(lines[i+1])
    else:
        indent2 = indent1
    new = lines[:i]
    partial = indent1
    while i < n and not is_all_white(lines[i]):
        # XXX Should take double space after period (etc.) into account
        words = re.split("(\s+)", lines[i])
        for j in range(0, len(words), 2):
            word = words[j]
            if not word:
                continue # Can happen when line ends in whitespace
            if len(string.expandtabs(partial + word)) > limit and \
               partial != indent1:
                new.append(string.rstrip(partial))
                partial = indent2
            partial = partial + word + " "
            if j+1 < len(words) and words[j+1] != " ":
                partial = partial + " "
        i = i+1
    new.append(string.rstrip(partial))
    # XXX Should reformat remaining paragraphs as well
    new.extend(lines[i:])
    return string.join(new, "\n")
开发者ID:alexei-matveev,项目名称:ccp1gui,代码行数:34,代码来源:FormatParagraph.py

示例13: get_url_contents

def get_url_contents(url):
    global lns
    lns = []
    url_comps = urlparse(url)
    if (url_comps[0] == "file"):
	f = open(url_comps[2])
	ln = f.readline()
	while ln:
	    lns.append(string.rstrip(ln))
	    ln = f.readline()
	f.close()
    elif (url_comps[0] == "ftp"):
	def ftp_line(ln):
	    lns.append(ln)
	h = ftplib.FTP(url_comps[1])
	h.login()
	i = string.rfind(url_comps[2], '/')
	if (i >= 0):
	    h.cwd(url_comps[2][:i])
	    h.retrlines("RETR "+url_comps[2][i+1:], ftp_line)
	else:
	    h.retrlines("RETR "+url_comps[2], ftp_line)
	h.close()
    elif (url_comps[0] == "http"):
	h = httplib.HTTP(url_comps[1])
	h.putrequest('GET', url_comps[2])
	h.putheader('Accept', 'text/html')
	h.putheader('Accept', 'text/plain')
	h.endheaders()
	errcode, errmsg, headers = h.getreply()
	# HTTP/1.1 replies seem to generate an errorcode of -1, so try
	# to handle this case.  This may simply be a manifestation of
	# a broken Python 1.4 httplib module.  This bug has been fixed
	# with Python version 1.5.
	version = sys.version[0:3]
	if ((version < "1.5") and (errcode == -1)):
	    try:
		real_errcode = string.atoi(string.split(errmsg)[1])
	    except ValueError:
		real_errcode = -1 # yes, it really is bogus :-/
	    sys.stderr.write("%d" % (real_errcode)) # Should be 200
	else:
	    sys.stderr.write("%d" % (errcode)) # Should be 200
            if (errcode == 200):
                f = h.getfile()
                ln = f.readline()
                # once again, try to compensate for broken behavior on HTTP/1.1
                # by eating the header lines which would otherwise show up in
                # the data.  This bug has been fixed with Python version 1.5.
                if ((version < "1.5") and (errcode == -1) and (real_errcode <> -1)):
                    while ((ln) and
                           ((len(ln) > 2) or
                            (ln[0] <> "\r") or (ln[-1] <> "\n"))):
                        ln = f.readline()
                while ln:
                    lns.append(string.rstrip(ln)) # Get the raw HTML
                    ln = f.readline()
                f.close()
    return lns
开发者ID:xosevp,项目名称:zmailer,代码行数:59,代码来源:spamlist.py

示例14: toHexString

def toHexString(bytes=[], format=0):
    """Returns an hex string representing bytes

        bytes:  a list of bytes to stringify,
                    e.g. [59, 22, 148, 32, 2, 1, 0, 0, 13]
        format: a logical OR of
                COMMA: add a comma between bytes
                HEX: add the 0x chars before bytes
                UPPERCASE: use 0X before bytes (need HEX)
                PACK: remove blanks

        example:
        bytes = [ 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 ]

        toHexString(bytes) returns  3B 65 00 00 9C 11 01 01 03

        toHexString(bytes, COMMA) returns  3B, 65, 00, 00, 9C, 11, 01, 01, 03

        toHexString(bytes, HEX) returns
            0x3B 0x65 0x00 0x00 0x9C 0x11 0x01 0x01 0x03

        toHexString(bytes, HEX | COMMA) returns
            0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03

        toHexString(bytes, PACK) returns  3B6500009C11010103

        toHexString(bytes, HEX | UPPERCASE) returns
            0X3B 0X65 0X00 0X00 0X9C 0X11 0X01 0X01 0X03

        toHexString(bytes, HEX | UPPERCASE | COMMA) returns
            0X3B, 0X65, 0X00, 0X00, 0X9C, 0X11, 0X01, 0X01, 0X03
    """

    from string import rstrip

    for byte in tuple(bytes):
        pass

    if type(bytes) is not list:
        raise TypeError('not a list of bytes')

    if bytes == None or bytes == []:
        return ""
    else:
        pformat = "%-0.2X"
        if COMMA & format:
            pformat = pformat + ","
        pformat = pformat + " "
        if PACK & format:
            pformat = rstrip(pformat)
        if HEX & format:
            if UPPERCASE & format:
                pformat = "0X" + pformat
            else:
                pformat = "0x" + pformat
        return rstrip(rstrip(
                reduce(lambda a, b: a + pformat % ((b + 256) % 256),
                        [""] + bytes)), ',')
开发者ID:acknowledge,项目名称:NFCGolfBallDispenser-API,代码行数:58,代码来源:lib.py

示例15: query

def query(track_info, server_url=default_server,
	  user=default_user, host=hostname, client_name=name,
          client_version=version, trying=0):

    disc_id = track_info[0]
    num_tracks = track_info[1]

    query_str = (('%08lx %d ') % (long(disc_id), num_tracks))

    for i in track_info[2:]:
	query_str = query_str + ('%d ' % i)
	
    query_str = urllib.quote_plus(string.rstrip(query_str))

    url = "%s?cmd=cddb+query+%s&hello=%s+%s+%s+%s&proto=%i" % \
	  (server_url, query_str, user, host, client_name,
           client_version, proto)

    response = urllib.urlopen(url)
    
    # Four elements in header: status, category, disc-id, title
    header = string.split(string.rstrip(response.readline()), ' ', 3)

    try:
        header[0] = string.atoi(header[0])
    except:
        if trying > 10:
            return [ 900, None ]
        return query(track_info, default_server,
                     default_user, hostname, name, version, trying+1)

    if header[0] == 200:		# OK
	result = { 'category': header[1], 'disc_id': header[2], 'title':
		   header[3] }

	return [ header[0], result ]

    elif header[0] == 211 or header[0] == 210: # multiple matches
	result = []

	for line in response.readlines():
	    line = string.rstrip(line)

	    if line == '.':		# end of matches
		break
					# otherwise:
					# split into 3 pieces, not 4
					# (thanks to bgp for the fix!)
	    match = string.split(line, ' ', 2)

	    result.append({ 'category': match[0], 'disc_id': match[1], 'title':
			    match[2] })

	return [ header[0], result ]

    else:
	return [ header[0], None ]
开发者ID:MattHung,项目名称:sage-graphics,代码行数:57,代码来源:CDDB.py


注:本文中的string.rstrip函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。