• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python string.replace函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: main

def main():
    print "in main"
    usage = "%prog -i inifile -o outputfile -s servers"
    parser = OptionParser(usage)
    parser.add_option("-s", "--servers", dest="servers")
    parser.add_option("-i", "--inifile", dest="inifile")
    parser.add_option("-o", "--outputFile", dest="outputFile")
    parser.add_option("-p", "--os", dest="os")
    options, args = parser.parse_args()

    print "the ini file is", options.inifile

    print "the server info is", options.servers

    servers = json.loads(options.servers)

    f = open(options.inifile)
    data = f.readlines()

    for i in range(len(data)):
        if "dynamic" in data[i]:
            data[i] = string.replace(data[i], "dynamic", servers[0])
            servers.pop(0)

        if options.os == "windows":
            if "root" in data[i]:
                data[i] = string.replace(data[i], "root", "Administrator")
            if "couchbase" in data[i]:
                data[i] = string.replace(data[i], "couchbase", "Membase123")

    for d in data:
        print d,

    f = open(options.outputFile, "w")
    f.writelines(data)
开发者ID:pkdevboxy,项目名称:testrunner,代码行数:35,代码来源:populateIni.py


示例2: find

 def find(self, string, pattern):
     word = string.replace(pattern,'*','\*')
     words = string.replace(word,' ','\s*')
     if re.search(words,string):
         pass
     else:
         raise log.err(string)
开发者ID:mspublic,项目名称:openair4G-mirror,代码行数:7,代码来源:core.py


示例3: parseFileName

def parseFileName(name):
    nameString = dropInsideContent(name,"[","]" )
    nameString = dropInsideContent(nameString,"{","}" )
    nameString = dropInsideContent(nameString,"(",")" )    
    nameString = nameString.strip('()_{}[][email protected]#$^&*+=|\\/"\'?<>~`')
    nameString = nameString.lstrip(' ')
    nameString = nameString.rstrip(' ')
    nameString = dropInsideContent(nameString,"{","}" )
    nameString = nameString.lower()
    nameString = string.replace(nameString,"\t"," ")
    nameString = string.replace(nameString,"  "," ")    
    
    try: 
        nameString = unicodedata.normalize('NFKD',nameString).encode()
        nameString = nameString.encode()
    except:
        try:
            nameString = nameString.encode('latin-1', 'ignore')
            nameString = unicodedata.normalize('NFKD',nameString).encode("ascii")
            nameString = str(nameString)
        except:
            nameString = "unknown"
    if len(nameString)==0: nameString=" "
    
    return nameString
开发者ID:javiermon,项目名称:albumart2mediaart,代码行数:25,代码来源:albumart2mediaart.py


示例4: filter_message

def filter_message(message):
	"""
	Filter a message body so it is suitable for learning from and
	replying to. This involves removing confusing characters,
	padding ? and ! with ". " so they also terminate lines
	and converting to lower case.
	"""
	# to lowercase
	message = string.lower(message)

	# remove garbage
	message = string.replace(message, "\"", "") # remove "s
	message = string.replace(message, "\n", " ") # remove newlines
	message = string.replace(message, "\r", " ") # remove carriage returns

	# remove matching brackets (unmatched ones are likely smileys :-) *cough*
	# should except out when not found.
	index = 0
	try:
		while 1:
			index = string.index(message, "(", index)
			# Remove matching ) bracket
			i = string.index(message, ")", index+1)
			message = message[0:i]+message[i+1:]
			# And remove the (
			message = message[0:index]+message[index+1:]
	except ValueError, e:
		pass
开发者ID:commonpike,项目名称:twittordrone,代码行数:28,代码来源:pyborg.py


示例5: get_director

	def get_director(self):
		self.director = re.findall(r'yseria\t+(.*)\t+scenariusz', self.page)
		if len(self.director)>0:
			self.director = self.director[0]
		self.director = string.replace(self.director, "\t",'')
		self.director = string.replace(self.director, ",",", ")
		self.director = string.replace(self.director, ",  (wi\xeacej&#160;...)",'')
开发者ID:BackupTheBerlios,项目名称:griffith-svn,代码行数:7,代码来源:PluginMovieFilmweb.py


示例6: createCFGFiles

def createCFGFiles(i,orgFile,basename,dir):

    newFile=basename + "_" + str(i) + ".py"
    newFile=os.path.join(dir,newFile)
    print(newFile)
    outFile = open(newFile,'w')
    
    for iline in orgFile:
        indx=string.find(iline,INPUTSTARTSWITH)
        if (indx == 0):
            indx2=string.find(iline,searchInput)
            if (indx2 < 0):
                print("Problem")
                sys.exit(1)
            else:
                iline=string.replace(iline,searchInput,str(i))
            
        indx=string.find(iline,OUTPUTSTARTSWITH)
        if (indx == 0):
            indx2=string.find(iline,searchOutput)
            if (indx2 < 0):
                print("Problem")
                sys.exit(1)
            else:
                replString="_" + str(i) + searchOutput
                iline=string.replace(iline,searchOutput,replString)
            
        outFile.write(iline + "\n")
    CloseFile(outFile)
    
    return newFile
开发者ID:Moanwar,项目名称:cmssw,代码行数:31,代码来源:CreateCFGs.py


示例7: sanitize

def sanitize(text):
    """
    Sanitizes text for referral URLS and for not found errors
    """
    text = string.replace(text, "<", "")
    text = string.replace(text, ">", "")
    return text
开发者ID:codejoust,项目名称:Stuff,代码行数:7,代码来源:html.py


示例8: four11Path

	def four11Path(self, filename411):
		"""Translates 411 file names into UNIX absolute filenames."""

		# Warning this is UNIX dependant
		n = string.replace(filename411, ".", "/")
		n = string.replace(n, "//", ".")
		return os.path.normpath(os.path.join(self.rootdir, n))
开发者ID:jeramirez,项目名称:base,代码行数:7,代码来源:service411.py


示例9: __normalize_dell_charset

 def __normalize_dell_charset(self, page_content):
     page_content = replace(page_content, "<sc'+'ript", '')
     page_content = replace(page_content, "</sc'+'ript", '')
     t = ''.join(map(chr, range(256)))
     d = ''.join(map(chr, range(128, 256)))
     page_content = page_content.translate(t, d)
     return page_content
开发者ID:jacob-carrier,项目名称:code,代码行数:7,代码来源:recipe-577056.py


示例10: render

    def render(self):
        form = self.request.params
        if not form.has_key("id"):
            return "ERROR No job specified"
        id = string.atoi(form["id"])
        if form.has_key("prefix"):
            prefix = form["prefix"]
            prefix = string.replace(prefix, '<', '')
            prefix = string.replace(prefix, '>', '')
            prefix = string.replace(prefix, '/', '')
            prefix = string.replace(prefix, '&', '')
            prefix = string.replace(prefix, '\\', '')
        elif form.has_key("phase") and form.has_key("test"):
            id = self.lookup_detailid(id, form["phase"], form["test"])
            if id == -1:
                return "ERROR Specified test not found"
            prefix = "test"
        else:
            prefix = ""

        try:
            filename = app.utils.results_filename(prefix, id)
            self.request.response.body_file = file(filename, "r")
            self.request.response.content_type="application/octet-stream"
            self.request.response.content_disposition = "attachment; filename=\"%d.tar.bz2\"" % (id)
            return self.request.response
        except Exception, e:
            if isinstance(e, IOError):
                # We can still report error to client at this point
                return "ERROR File missing"
            else:
                return "ERROR Internal error"
开发者ID:johnmdilley,项目名称:xenrt,代码行数:32,代码来源:files.py


示例11: precmd

	def precmd(self, line):
		"""Handle alias expansion and ';;' separator."""
		if not line:
			return line
		args = string.split(line)
		while self.aliases.has_key(args[0]):
			line = self.aliases[args[0]]
			ii = 1
			for tmpArg in args[1:]:
				line = string.replace(line, "%" + str(ii),
						      tmpArg)
				ii = ii + 1
			line = string.replace(line, "%*",
					      string.join(args[1:], ' '))
			args = string.split(line)
		# split into ';;' separated commands
		# unless it's an alias command
		if args[0] != 'alias':
			marker = string.find(line, ';;')
			if marker >= 0:
				# queue up everything after marker
				next = string.lstrip(line[marker+2:])
				self.cmdqueue.append(next)
				line = string.rstrip(line[:marker])
		return line
开发者ID:asottile,项目名称:ancient-pythons,代码行数:25,代码来源:pdb.py


示例12: render_admin_panel

    def render_admin_panel(self, req, cat, page, path_info):
        req.perm.require('TRAC_ADMIN')

        status, message = init_admin(self.gitosis_user, self.gitosis_server, self.admrepo, self.env.path)
        data = {}
        if status != 0:
          add_warning(req, _('Error while cloning gitosis-admin repository. Please check your settings and/or passphrase free connection to this repository for the user running trac (in most cases, the web server user)'))
          message = 'return code: '+str(status)+'\nmessage:\n'+message
          if message:
            add_warning(req, _(message))
        repo = replace(os.path.basename(self.config.get('trac', 'repository_dir')), '.git', '')
        if req.method == 'POST':
            config = {}
            self.log.debug('description: '+req.args.get('description'))
            for option in ('daemon', 'gitweb', 'description', 'owner'):
                 config[option] = req.args.get(option)
            self.set_config(repo, config)
            req.redirect(req.href.admin(cat, page))
        repo = replace(os.path.basename(self.config.get('trac', 'repository_dir')), '.git', '')
        if repo != '':
            data = self.get_config(repo)
        self.log.debug('data: %s', str(data))
        if not data:
            data = {}
        for option in ('daemon', 'gitweb', 'description', 'owner'):
            if option not in data:
                data[option] = ''
        data['gitweb'] = data['gitweb'] in _TRUE_VALUES
        data['daemon'] = data['daemon'] in _TRUE_VALUES
        return 'admin_tracgitosis_repo.html', {'repo': data}
开发者ID:metalefty,项目名称:TracGitosisPlugin,代码行数:30,代码来源:tracgitosis.py


示例13: search

 def search(self, pattern='', context=''):
     pattern = string.replace(string.lower(pattern),'*','%')
     pattern = string.replace(string.lower(pattern),'?','_')
     if pattern:
         return self.select("context LIKE '%s'" % pattern, orderBy="context")
     else:
         return self.select(orderBy="context")
开发者ID:BackupTheBerlios,项目名称:esm-svn,代码行数:7,代码来源:Setting.py


示例14: normalize

def normalize(string):
	string = string.replace(u"Ä", "Ae").replace(u"ä", "ae")
	string = string.replace(u"Ö", "Oe").replace(u"ö", "oe")
	string = string.replace(u"Ü", "Ue").replace(u"ü", "ue")
	string = string.replace(u"ß", "ss")
	string = string.encode("ascii", "ignore")
	return string
开发者ID:raumzeitlabor,项目名称:rzlphlog,代码行数:7,代码来源:rzlphlog.py


示例15: get_rendereable_badgeset

def get_rendereable_badgeset(account):
  """
  Will return a badgset as follows:
  theme
   -badgeset
    name
    description
    alt
    key
    perm(issions)
  """
  badges = get_all_badges_for_account(account)
  badgeset = []
  
  for b in badges:
    """ Badge id is theme-name-perm. spaces and " " become "-" """
    name_for_id = string.replace(b.name, " ", "_")
    name_for_id = string.replace(name_for_id, "-", "_")
    
    theme_for_id = string.replace(b.theme, " ", "_")
    theme_for_id = string.replace(theme_for_id, "-", "_")
    
    badge_id = theme_for_id + "-" + name_for_id + "-" + b.permissions 
  
    item = {"name": b.name,
            "description": b.description,
            "alt":b.altText,
            "key":b.key().name(),
            "perm":b.permissions,
            "theme" : b.theme,
            "id": badge_id,
            "downloadLink":b.downloadLink}
    badgeset.append(item)
  return badgeset
开发者ID:AkilDixon,项目名称:UserInfuser,代码行数:34,代码来源:badges_dao.py


示例16: get_plot

 def get_plot(self):
     self.plot = gutils.trim(self.page,"<td valign=\"top\" align=\"left\">","</td>")
     self.plot = string.strip(self.plot.decode('latin-1'))
     self.plot = string.replace(self.plot,"<br>", " ")
     self.plot = string.replace(self.plot,"<p>", " ")
     self.plot = string.replace(self.plot,"'","_")
     self.plot = string.strip(gutils.strip_tags(self.plot))
开发者ID:BackupTheBerlios,项目名称:griffith-svn,代码行数:7,代码来源:PluginMovieMediadis.py


示例17: CleanFileData

 def CleanFileData(self, data):
     """ clean the read file data and return it """
     fresh = []
     for i in data:
         if string.strip(string.replace(i, '\012', '')) != '':
             fresh.append(string.strip(string.replace(i, '\012', '')))
     return fresh
开发者ID:rbe,项目名称:dmerce,代码行数:7,代码来源:ConvertTime.py


示例18: get_genre

 def get_genre(self):
     self.genre = gutils.trim(self.page,"Genre(s):","</table>")
     self.genre = string.replace(self.genre, "<br>", ", ")
     self.genre = gutils.strip_tags(self.genre)
     self.genre = string.replace(self.genre, "/", ", ")
     self.genre = gutils.clean(self.genre)
     self.genre = self.genre[0:-1]
开发者ID:BackupTheBerlios,项目名称:griffith-svn,代码行数:7,代码来源:PluginMovieOFDb.py


示例19: createLSFScript

def createLSFScript(cfgfile):

    file=os.path.basename(cfgfile)
    absDir=os.path.abspath(os.path.dirname(cfgfile))
    
    
    outScript="runlsf_" + string.replace(file,".py",".csh")
    outLog="runlsf_" + string.replace(file,".py",".log")

    inScript=os.path.join(file)
    outScript=os.path.join(absDir,outScript)
    outLog=os.path.join(absDir,outLog)

    oFile = open(outScript,'w')
    oFile.write("#!/bin/csh" + "\n")
    #oFile.write("\n")    
    oFile.write("cd " + absDir + "\n")
    oFile.write("eval `scram runtime -csh`" +  "\n")
    #oFile.write("\n")
    oFile.write("cmsRun " + inScript + "\n")    
    #oFile.write("date" + "\n")
    
    oFile.close()
    
    return
开发者ID:Moanwar,项目名称:cmssw,代码行数:25,代码来源:CreateCFGs.py


示例20: loadFile

def loadFile(fileName, width, height):
    """ 
    Loads skin xml file and resolves embedded #include directives.
    Returns completely loaded file as a string. 
    """
        
    log.debug("loadFile(%s, %d, %d)"%(fileName, width, height ) )
    s = ""
    f = file( fileName )
    for l in f.readlines():
        # log.debug(fileName + ":" + l) 
        m = sre.match( '^#include (.*)$', l )
        if m:
            incFile = m.group(1)
            incFile = incFile.strip()
            if sre.match( '^\w+\.xml$', incFile ):
                # need to find skin file
                incFile = findSkinFile( incFile, width, height )
            elif sre.match( '\%SKINDIR\%', incFile ):
                incFile = string.replace(incFile, "%SKINDIR%", getSkinDir())
            else:
                # convert path separators to proper path separator - just in case
                incFile = string.replace( incFile, "/", os.sep )
                incFile = string.replace( incFile, "\\", os.sep )

                # assume relative path provided
                path = os.path.dirname( fileName )
                path += os.sep + incFile
                incFile = path
            s += loadFile( incFile, width, height )
        else:
            s += l
    f.close()
    return s
开发者ID:Bram77,项目名称:xbmc-favorites,代码行数:34,代码来源:util.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python string.rfind函数代码示例发布时间:2022-05-27
下一篇:
Python string.maketrans函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap