本文整理汇总了Python中string.strip函数的典型用法代码示例。如果您正苦于以下问题:Python strip函数的具体用法?Python strip怎么用?Python strip使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了strip函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
global stack
name = sys.argv[1]
arch = getArchive(name)
stack.append((name, arch))
show(name, arch)
while 1:
toks = string.split(raw_input('? '), ' ', 1)
if not toks:
usage()
continue
if len(toks) == 1:
cmd = toks[0]
arg = ''
else:
cmd, arg = toks
cmd = string.upper(cmd)
if cmd == 'U':
if len(stack) > 1:
arch = stack[-1][1]
arch.lib.close()
del stack[-1]
nm, arch = stack[-1]
show(nm, arch)
elif cmd == 'O':
if not arg:
arg = raw_input('open name? ')
arg = string.strip(arg)
arch = getArchive(arg)
if arch is None:
print arg, "not found"
continue
stack.append((arg, arch))
show(arg, arch)
elif cmd == 'X':
if not arg:
arg = raw_input('extract name? ')
arg = string.strip(arg)
data = getData(arg, arch)
if data is None:
print "Not found"
continue
fnm = raw_input('to filename? ')
if not fnm:
print `data`
else:
open(fnm, 'wb').write(data)
elif cmd == 'Q':
break
else:
usage()
for (nm, arch) in stack:
arch.lib.close()
stack = []
for fnm in cleanup:
try:
os.remove(fnm)
except Exception, e:
print "couldn't delete", fnm, e.args
示例2: dropbox_init
def dropbox_init(dropbox_app_key,dropbox_app_secret):
from dropbox import client, rest, session
APP_KEY = dropbox_app_key
APP_SECRET = dropbox_app_secret
ACCESS_TYPE = 'app_folder'
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
oauth_token = ''
oauth_token_secret = ''
f = open("dropbox_token.txt",'r')
if f:
oauth_token = string.strip(f.readline())
oauth_token_secret = string.strip(f.readline())
f.close()
if oauth_token == '' or oauth_token_secret == '':
request_token = sess.obtain_request_token()
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please visit this website and press the 'Allow' button, then hit 'Enter' here."
raw_input()
access_token = sess.obtain_access_token(request_token)
f = open("dropbox_token.txt","wb")
f.write(access_token.key + '\n')
f.write(access_token.secret)
f.close()
else:
sess.set_token(oauth_token, oauth_token_secret)
client = client.DropboxClient(sess)
#print "linked account:", client.account_info()
return client
示例3: readmailcapfile
def readmailcapfile(fp):
caps = {}
while 1:
line = fp.readline()
if not line: break
# Ignore comments and blank lines
if line[0] == '#' or string.strip(line) == '':
continue
nextline = line
# Join continuation lines
while nextline[-2:] == '\\\n':
nextline = fp.readline()
if not nextline: nextline = '\n'
line = line[:-2] + nextline
# Parse the line
key, fields = parseline(line)
if not (key and fields):
continue
# Normalize the key
types = string.splitfields(key, '/')
for j in range(len(types)):
types[j] = string.strip(types[j])
key = string.lower(string.joinfields(types, '/'))
# Update the database
if caps.has_key(key):
caps[key].append(fields)
else:
caps[key] = [fields]
return caps
示例4: getGcor
def getGcor(tpDic1, tpDic2):
tmpf1 = open("/home/dk/tmp/1.txt","w")
for ap1 in sorted(tpDic1.keys()):
line = ""
for ap2 in sorted(tpDic1.keys()):
line = line + str(tpDic1[ap1][ap2]) + " "
line = string.strip(line)
print >> tmpf1, line
tmpf1.close()
tmpf2 = open("/home/dk/tmp/2.txt","w")
for ap1 in sorted(tpDic2.keys()):
line = ""
for ap2 in sorted(tpDic2.keys()):
line = line + str(tpDic2[ap1][ap2]) + " "
line = string.strip(line)
print >> tmpf2, line
tmpf2.close()
rscript = """
library(sna)
g1 <- as.matrix(read.table(file="/home/dk/tmp/1.txt", header=F))
g2 <- as.matrix(read.table(file="/home/dk/tmp/2.txt", header=F))
gcor(g1[2:93,2:93],g2[2:93,2:93])
"""
try:
return float(r(rscript)[0])
except:
return 0.0
示例5: formatElement
def formatElement(el,path):
if (el.find("{http://www.w3.org/2001/XMLSchema}annotation") is not None):
splitPath=string.split(path,'/')
#set default component to "scenario", i.e. write to the "Scenario" worksheet below
component="scenario"
printPath=string.replace(path,"/"+component,"")
#update component if a know child element of scenario, i.e. write to another worksheet below
if (len(splitPath)>2):
if (splitPath[2] in worksheets):
component=splitPath[2]
printPath=string.replace(printPath,"/"+component,"")
sheet= worksheets[component][0]
row=worksheets[component][1]
sheet.write(row,0,string.lstrip(printPath,"/"))
annotation=el.find("{http://www.w3.org/2001/XMLSchema}annotation")
docuElem=annotation.find("{http://www.w3.org/2001/XMLSchema}documentation")
if (docuElem is not None):
docu=docuElem.text
else:
docu="TODO"
content=string.strip(docu)
sheet.write(row,1,normalizeNewlines(content),docu_xf)
appInfoElem=el.find("{http://www.w3.org/2001/XMLSchema}annotation").find("{http://www.w3.org/2001/XMLSchema}appinfo")
if (appInfoElem is not None):
appInfo=string.strip(appInfoElem.text)
else:
appInfo="name:TODO"
appInfoList=string.split(appInfo,";")[0:-1]
for keyValue in appInfoList:
splitPair=string.split(keyValue,":")
colIndex=appinfoOrder.index(string.strip(str(splitPair[0])))+2
sheet.write(row,colIndex,splitPair[1],docu_xf)
#update next row to be written in that sheet
worksheets[component][1]=worksheets[component][1]+1
示例6: GetAliveMachinesWithVersions
def GetAliveMachinesWithVersions(machines, config):
cmd = ". %s; cd %s/enterprise/legacy/util; ./get_config_version.py %s" % (
config.ENTERPRISE_BASHRC, config.MAIN_GOOGLE3_DIR, config.ENTERPRISE_HOME)
(err, out) = commands.getstatusoutput(
". %s;cd %s/enterprise/legacy/util; ./ent_exec.py -q -a60 -b "\
" -m \"%s\" -x \"%s\"" % (
config.ENTERPRISE_BASHRC, config.MAIN_GOOGLE3_DIR,
string.join(machines, " "), cmd))
out = string.split(out, "\n")
out = map(lambda p: string.split(p, "-"), out)
out = filter(lambda p: len(p) == 2, out)
ret = []
for (version, machine) in out:
try:
ret.append((int(version), string.strip(machine)))
except ValueError:
# An Invalid answer is punished
ret.append((0, string.strip(machine)))
# if we have less than 1/2 of machines, something is wrong... return Nonr
if len(machines)/2 >= len(ret):
return None
# else we return what we got
ret.sort()
return ret
示例7: slotSave
def slotSave(self):
"""Save the new account. Called when Save-button clicked
"""
#First, is this really a new account?
if self._accountL.getByNum(string.strip(str(self.wAccNum.text()))):
QMessageBox.information(self, Model.Global.getAppName(),
str(self.tr("This account already exists.")) + '\n' +
str(self.tr("Please chose a new account number.")))
else: #no, make a new account object and fill in from fields
o= Model.Account.Account()
try:
o.num= string.strip(str(self.wAccNum.text()))
o.name= string.strip(str(self.wAccName.text()))
if self.useVat == 'Y':
o.defVat= str(self.wVat.currentItem())
else: o.defVat= '0'
if self.useBudget=='Y':
o.budget= Model.Global.moneyToInt(
str(self.wBudget.text()))
else: o.budget= 0
except Model.Exceptions.VarLimit, s: #An unacceptable value
try: # approporiate error message?
m= str(self.tr(e[s[1]]))
except KeyError: #No, make a substitute
m= str(self.tr("Error text for '%s' is not defined"))%s[1]
msg= m + str(self.tr(
'\nPlease fix,\nThis account was not saved.'))
QMessageBox.information(self, Model.Global.getAppName(), msg)
return # and let the user correct
self._accountL.saveEntry(o)
self.emit(PYSIGNAL('account'), (o, 'N')) # Tell the world
self.slotNew()
示例8: process
def process(fn, s, e):
"""
Actually process the file!
"""
lines = open(fn, 'r').readlines()
for line in lines:
if line.find(",") == -1:
continue
if (line[0] == "*"):
stationID = string.upper(line[3:10])
dc = re.split(",", line)[1:-1]
dcols = []
for c in dc:
dcols.append("c"+ string.strip(c))
dcols.append("c"+ string.strip(c) +"_f")
continue
tokens = re.split(",", line)
if len(tokens) < 4:
break
ts = mx.DateTime.DateTime(int(tokens[2]), int(tokens[0]), int(tokens[1]))
# If this row is an hourly ob
if int(dc[0]) == 100:
ts = make_time( tokens[2], tokens[0], tokens[1], tokens[3])
if ts < e:
tstring = ts.strftime("%Y-%m-%d %H:%M")
for i in range(len(dcols)):
if not obs.has_key(stationID) or not obs[stationID].has_key(tstring):
continue
val = tokens[4+i].strip()
if val == "" or val.find("*") > -1:
val = None
try:
obs[stationID][tstring][ dcols[i] ] = val
except:
print stationID, dcols, i, val
示例9: runner
def runner(bndyargs, filename):
# excstring = "(cd " + pathprefix + "; " + "python testbdy.py " +\
# bndyargs + " )"
excstring = "python testbdy.py " + bndyargs
digitsplus = "[-"+string.digits+"]"
pipe = os.popen(excstring, 'r')
file = open(pathprefix+filename,'r')
mismatch = None
lct = 0
for linestring in file.readlines():
lct+=1
if re.match(digitsplus,linestring[0]):
# Get next string from the pipe that looks like data.
pipestring = pipe.readline()
while not re.match(digitsplus, pipestring[0]):
pipestring = pipe.readline()
#
lineset = string.split(linestring, ' ')
pipeset = string.split(pipestring, ' ')
# Compare data entries, howevermany there are.
for (linevalue, pipevalue) in map(None, lineset, pipeset):
if abs(float(linevalue)-float(pipevalue)) > tolerance:
mismatch = 1
print "\nMismatch, line %d in file %s." % (lct, filename)
print " File: " + string.strip(linevalue)
print "Program: " + string.strip(pipevalue)
else:
# Discard pipe data.
pipe.readline()
if mismatch:
print "Failed on file %s." % filename
else:
print "File %s OK." % filename
示例10: characters
def characters(self,chars):
if "copy" in self.zone and ((len(self.zone) > 1 and self.zone[1] in self.fases) or (self.fases == ["all"])):
if len(string.strip(chars)):
resul = checkvars(self.properties,self.attribs,string.strip(chars),self.debuglevel)
from_file = resul[1]
if not resul[0]:
if os.access(from_file, os.R_OK):
self.copyaux[0].append(from_file)
to_file = self.attribs["layout"]["to"] + self.attribs["copy"]["to"] + from_file.split("/")[-1]
if os.path.isfile(from_file) or os.path.isdir(from_file):
if to_file in self.archives and self.debuglevel >= 1: print "W: El fichero", to_file, "existe, se sobreescribirá"
self.archives.append(to_file)
else:
self.error.append("E: Fichero origen no existe: %s" % from_file)
else:
self.error.append("E: El fichero %s no existe o no es accesible para lectura"%(from_file))
else:
if not from_file in self.error:
self.error.append(from_file)
elif "textfile" in self.zone and len(chars.strip()):
resul = checkvars(self.properties,self.attribs,chars.strip(),self.debuglevel)
if not resul[0]:
self.textfile.append(resul[1])
elif "include" in self.zone and len(chars.strip()):
resul = checkvars(self.properties,self.attribs,chars.strip(),self.debuglevel)
if not resul[0]:
self.includes.append(resul[1])
elif "description" in self.zone and len(chars.strip()):
resul = checkvars(self.properties,self.attribs,chars.strip(),self.debuglevel)
if not resul[0]:
self.properties["info.description"] = resul[1]
示例11: precontext
def precontext(self):
# Scan back for the identifier currently being typed.
line, pos = self.cursor()
command = self.getline()
preceding = command[:pos]
startchars = string.letters + "_"
identchars = string.letters + string.digits + "_"
while pos > 0 and preceding[pos-1] in identchars:
pos = pos - 1
preceding, ident = preceding[:pos], preceding[pos:]
start = "%d.%d" % (line, pos)
preceding = string.strip(preceding)
context = ""
if not ident or ident[0] in startchars:
# Look for context before the start of the identifier.
while preceding[-1:] == ".":
preceding = string.strip(preceding[:-1])
if preceding[-1] in identchars:
pos = len(preceding)-1
while pos > 0 and preceding[pos-1] in identchars:
pos = pos - 1
if preceding[pos] in startchars:
context = preceding[pos:] + "." + context
preceding = string.strip(preceding[:pos])
else: break
else: break
line, pos = self.cursor()
endpos = pos
while endpos < len(command) and command[endpos] in identchars:
endpos = endpos + 1
end = "%d.%d" % (line, endpos)
return command, context, ident, start, end
示例12: manageSubjectsProperties
def manageSubjectsProperties(self, ids=[], old_code='', code='', name='', REQUEST=None):
""" manage subjects for EEAGlossaryEngine """
if self.utAddObjectAction(REQUEST):
if string.strip(code) == '' or string.strip(name) == '':
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=3')
else:
if self.check_subjects_exists(code):
self.set_subjects_list(code, name)
self._p_changed = 1
else:
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=3')
elif self.utUpdateObjectAction(REQUEST):
if string.strip(code) == '' or string.strip(name) == '':
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=3')
else:
self.del_subject_from_list(old_code)
self.set_subjects_list(code, name)
self._p_changed = 1
elif self.utDeleteObjectAction(REQUEST):
if not ids or len(ids) == 0:
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=3')
for subj in self.utConvertToList(ids):
self.del_subject_from_list(subj)
self._p_changed = 1
if REQUEST is not None:
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=3&save=ok')
示例13: manageStopWordsProperties
def manageStopWordsProperties(self, ids='', stop_word='', old_stop_word='', REQUEST=None):
""" manage stop words for EEAGlossaryEngine """
if self.utAddObjectAction(REQUEST):
if string.strip(stop_word)=='':
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=6')
else:
if self.check_stop_words_exists(stop_word):
self.set_stop_words_list(stop_word)
self._p_changed = 1
else:
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=6')
elif self.utUpdateObjectAction(REQUEST):
if string.strip(stop_word)=='':
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=6')
else:
self.del_stop_words_from_list(old_stop_word)
self.set_stop_words_list(stop_word)
self._p_changed = 1
elif self.utDeleteObjectAction(REQUEST):
if not ids or len(ids) == 0:
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=6')
for word in self.utConvertToList(ids):
self.del_stop_words_from_list(word)
self._p_changed = 1
if REQUEST is not None:
return REQUEST.RESPONSE.redirect('manage_properties_html?pagetab=6&save=ok')
示例14: ssh_keygen
def ssh_keygen(logger):
"""using pexpect to generate RSA"""
logger.info("generate ssh RSA \"%s\"" % SSH_KEYGEN)
child = pexpect.spawn(SSH_KEYGEN)
while True:
index = child.expect(['Enter file in which to save the key ',
'Enter passphrase ',
'Enter same passphrase again: ',
pexpect.EOF,
pexpect.TIMEOUT])
if index == 0:
child.sendline("\r")
elif index == 1:
child.sendline("\r")
elif index == 2:
child.sendline("\r")
elif index == 3:
logger.debug(string.strip(child.before))
child.close()
return 0
elif index == 4:
logger.error("ssh_keygen timeout")
logger.debug(string.strip(child.before))
child.close()
return 1
return 0
示例15: checkAuthorization
def checkAuthorization(self, authorization, password, nonce, method="REGISTER"):
hash = {}
list = authorization.split(",")
for elem in list:
md = rx_kv.search(elem)
if md:
value = string.strip(md.group(2),'" ')
key = string.strip(md.group(1))
hash[key]=value
# check nonce (response/request)
if hash["nonce"] != nonce:
self.server.main_logger.warning("SIP: Authentication: Incorrect nonce")
return False
a1="%s:%s:%s" % (hash["username"],hash["realm"], password)
a2="%s:%s" % (method, hash["uri"])
ha1 = hashlib.md5(a1).hexdigest()
ha2 = hashlib.md5(a2).hexdigest()
b = "%s:%s:%s" % (ha1,nonce,ha2)
expected = hashlib.md5(b).hexdigest()
if expected == hash["response"]:
self.server.main_logger.debug("SIP: Authentication: succeeded")
return True
self.server.main_logger.warning("SIP: Authentication: expected= %s" % expected)
self.server.main_logger.warning("SIP: Authentication: response= %s" % hash["response"])
return False