本文整理汇总了Python中string.replace函数的典型用法代码示例。如果您正苦于以下问题:Python replace函数的具体用法?Python replace怎么用?Python replace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了replace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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
示例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
示例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 ...)",'')
示例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
示例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
示例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))
示例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
示例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"
示例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
示例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}
示例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")
示例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
示例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