本文共 18950 字,大约阅读时间需要 63 分钟。
本文整理匯總了Python中string.rfind方法的典型用法代碼示例。如果您正苦於以下問題:Python string.rfind方法的具體用法?Python string.rfind怎麽用?Python string.rfind使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在模塊string的用法示例。
在下文中一共展示了string.rfind方法的26個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1: parseJavaScriptCalls
點讚 6
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def parseJavaScriptCalls():
global database_js
"""
Parse the JavaScript and download the files
"""
for j in database_js:
jsName = j[j.rfind('/')+1:]
if not os.path.exists('local/js/' + jsName):
# first download the file
dl(j,'local/js/' + jsName)
try:
jsContent = open('local/js/' + jsName, 'r')
except IOError:
continue
parseJavaScriptContent(jsContent)
jsContent.close()
開發者ID:penetrate2hack,項目名稱:ITWSV,代碼行數:18,
示例2: printexpr
點讚 6
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
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]))
開發者ID:ActiveState,項目名稱:code,代碼行數:18,
示例3: lineReceived
點讚 6
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def lineReceived(self, line):
parts = string.split(line)
if not parts:
parts = ['']
if len(parts) == 1:
slash_w = 0
else:
slash_w = 1
user = parts[-1]
if '@' in user:
host_place = string.rfind(user, '@')
user = user[:host_place]
host = user[host_place+1:]
return self.forwardQuery(slash_w, user, host)
if user:
return self.getUser(slash_w, user)
else:
return self.getDomain(slash_w)
開發者ID:kuri65536,項目名稱:python-for-android,代碼行數:20,
示例4: _fixupParents
點讚 6
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def _fixupParents(self, alogger):
"""
Ensure that there are either loggers or placeholders all the way
from the specified logger to the root of the logger hierarchy.
"""
name = alogger.name
i = string.rfind(name, ".")
rv = None
while (i > 0) and not rv:
substr = name[:i]
if not self.loggerDict.has_key(substr):
self.loggerDict[substr] = PlaceHolder(alogger)
else:
obj = self.loggerDict[substr]
if isinstance(obj, Logger):
rv = obj
else:
assert isinstance(obj, PlaceHolder)
obj.append(alogger)
i = string.rfind(name, ".", 0, i - 1)
if not rv:
rv = self.root
alogger.parent = rv
開發者ID:ofermend,項目名稱:medicare-demo,代碼行數:25,
示例5: fetch
點讚 6
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def fetch(file):
if base_url in file:
dir = file[len(base_url) - 1:rfind(file, '/') + 1]
file = file[rfind(file, '/') + 1:]
elif 'http' in file:
return
else:
dir = '/'
process(dir + file)
base_dir = path.dirname(dir + file)
if base_dir != '/':
base_dir += '/'
tree = ElementTree.parse(out_dir + dir + file)
for element in tree.getiterator():
if element.tag.split('}')[1] == 'url':
if element.text[-4:] != '.xml':
if not 'http' in element.text:
process(base_dir + element.text)
else:
fetch(element.text)
開發者ID:opencas,項目名稱:mirrord,代碼行數:22,
示例6: makeRoot
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def makeRoot(urlLocal):
if allowedExtensions(urlLocal):
return urlLocal[0:urlLocal.rfind('/')+1]
return urlLocal
開發者ID:penetrate2hack,項目名稱:ITWSV,代碼行數:6,
示例7: giveGoodURL
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def giveGoodURL(href, urlLocal):
"""
It should return a good url...
href = argument retrieven from the href...
"""
if 'javascript' in href:
return htmldecode(urlLocal)
if 'http://' in href or 'https://' in href:
if urlLocal in href:
return htmldecode(href)
else:
return urlLocal
if len(href) < 1:
return htmldecode(urlLocal)
if href[0] == '?' and '?' not in urlLocal and not allowedExtensions(urlLocal):
for e in allowed:
if '.'+e in urlLocal:
return htmldecode(urlLocal + href)
return htmldecode(urlLocal + '/' + href)
else:
# simple name
if allowedExtensions(urlLocal) or '?' in urlLocal:
return htmldecode(urlLocal[0:urlLocal.rfind('/')+1] + href)
else:
return htmldecode(urlLocal + '/' + href)
return htmldecode(href)
開發者ID:penetrate2hack,項目名稱:ITWSV,代碼行數:28,
示例8: rfindFirstJSChars
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def rfindFirstJSChars(string):
b = [string.rfind(k) for k in jsChars]
return max(b)
開發者ID:penetrate2hack,項目名稱:ITWSV,代碼行數:5,
示例9: collectintargz
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is chagned
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the source list for.
#sources = [s for s in sources if not (s in target)]
sources = filter(lambda s, t=target: not (s in t), sources)
# find the .spec file for rpm and add it since it is not necessarily found
# by the FindSourceFiles function.
#sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
spec_file = lambda s: string.rfind(str(s), '.spec') != -1
sources.extend( filter(spec_file, source) )
# as the source contains the url of the source package this rpm package
# is built from, we extract the target name
#tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
tarball = string.replace(str(target[0])+".tar.gz", '.rpm', '')
try:
#tarball = env['SOURCE_URL'].split('/')[-1]
tarball = string.split(env['SOURCE_URL'], '/')[-1]
except KeyError as e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
PACKAGEROOT=env['PACKAGEROOT'], )
return (target, tarball)
開發者ID:coin3d,項目名稱:pivy,代碼行數:32,
示例10: rightmost_separator
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def rightmost_separator(path, sep, _altsep=_altsep):
rfind = string.rfind
return max(rfind(path, sep), rfind(path, _altsep))
開發者ID:coin3d,項目名稱:pivy,代碼行數:5,
示例11: splitext
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def splitext(path):
"Same as os.path.splitext() but faster."
sep = rightmost_separator(path, os.sep)
dot = string.rfind(path, '.')
# An ext is only real if it has at least one non-digit char
if dot > sep and not containsOnly(path[dot:], "0123456789."):
return path[:dot],path[dot:]
else:
return path,""
開發者ID:coin3d,項目名稱:pivy,代碼行數:11,
示例12: RegGetValue
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def RegGetValue(root, key):
"""This utility function returns a value in the registry
without having to open the key first. Only available on
Windows platforms with a version of Python that can read the
registry. Returns the same thing as
SCons.Util.RegQueryValueEx, except you just specify the entire
path to the value, and don't have to bother opening the key
first. So:
Instead of:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion')
out = SCons.Util.RegQueryValueEx(k,
'ProgramFilesDir')
You can write:
out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
"""
# I would use os.path.split here, but it's not a filesystem
# path...
p = key.rfind('\\') + 1
keyp = key[:p-1] # -1 to omit trailing slash
val = key[p:]
k = RegOpenKeyEx(root, keyp)
return RegQueryValueEx(k,val)
開發者ID:coin3d,項目名稱:pivy,代碼行數:28,
示例13: my_import
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def my_import(mname):
if '.' in mname:
i = string.rfind(mname, '.')
parent = my_import(mname[:i])
fp, pathname, description = imp.find_module(mname[i+1:],
parent.__path__)
else:
fp, pathname, description = imp.find_module(mname)
return imp.load_module(mname, fp, pathname, description)
開發者ID:coin3d,項目名稱:pivy,代碼行數:11,
示例14: authentication_hash_validate
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def authentication_hash_validate():
"""
This function is called to check if a username /
password combination is valid.
"""
def last_occurence_delete(string, character):
index = string.rfind(character)
if index is None or index < 0:
return string
return string[:index] + string[index + 1:]
hash_response = str(flask.request.headers.get('Authorization', ''))
if len(hash_response) == 0:
return False
hash_challenge_list = []
# Check normal url
url = str(flask.request.url)
hash_challenge = get_url_authorization(url)
hash_challenge_list.append(hash_challenge)
# If hash at the end of the url, try alternate hash as well
url = last_occurence_delete(url, '/')
hash_challenge = get_url_authorization(url)
hash_challenge_list.append(hash_challenge)
if '?' in url:
url.replace('?', '/?')
hash_challenge = get_url_authorization(url)
hash_challenge_list.append(hash_challenge)
return hash_response in hash_challenge_list
開發者ID:Erotemic,項目名稱:ibeis,代碼行數:30,
示例15: parse_primitive_type
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def parse_primitive_type(col):
idx = string.find(col, '(')
ridx = string.rfind(col, ')')
if idx < 0 and ridx < 0:
return [col]
elif idx > 0 and ridx > 0:
type = col[: idx].strip()
specs = col[idx + 1 : ridx]
specs = specs.split(',')
specs = map(str.strip, specs)
return [type, specs]
else:
raise RuntimeError("Invalid primitive type: " + col)
開發者ID:exasol,項目名稱:script-languages,代碼行數:15,
示例16: _search
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def _search(self, data, text, start, previous=False):
self._lastText = text
if text == '':
return -1
if not previous:
idx1 = string.find(data, text, start)
text1 = '\0'.join(text)
idx2 = string.find(data, text1, start)
idx = idx1
if idx1 == -1:
idx = idx2
else:
if idx2 < idx1 and idx2 != -1:
idx = idx2
else:
idx1 = string.rfind(data, text, 0, start)
text1 = '\0'.join(text)
idx2 = string.rfind(data, text1, 0, start)
idx = idx1
if idx1 == -1:
idx = idx2
else:
if idx2 > idx1 and idx2 != -1:
idx = idx2
if idx > -1:
self._lastIdx = idx
if idx > -1:
self._viewMode.selector.addSelection((idx, idx + len(text), QtGui.QBrush(QtGui.QColor(125, 0, 100)), 0.8) , type=TextSelection.SelectionType.NORMAL)
self._viewMode.goTo(idx)
return idx
開發者ID:xtiankisutsa,項目名稱:MARA_Framework,代碼行數:43,
示例17: get_leafname
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def get_leafname(path):
"""Get the leafname of the specified file."""
pos = string.rfind(path, os.sep)
if pos != -1:
return path[pos+1:]
else:
return path
開發者ID:google,項目名稱:myelin-acorn-electron-hardware,代碼行數:10,
示例18: format_error
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def format_error(input, err, scanner):
"""This is a really dumb long function to print error messages nicely."""
error_message = StringIO.StringIO()
p = err.pos
print >> error_message, "error position", p
# Figure out the line number
line = count(input[:p], '\n')
print >> error_message, err.msg, "on line", repr(line+1) + ":"
# Now try printing part of the line
text = input[max(p-80, 0):p+80]
p = p - max(p-80, 0)
# Strip to the left
i = rfind(text[:p], '\n')
j = rfind(text[:p], '\r')
if i < 0 or (0 <= j < i): i = j
if 0 <= i < p:
p = p - i - 1
text = text[i+1:]
# Strip to the right
i = find(text,'\n', p)
j = find(text,'\r', p)
if i < 0 or (0 <= j < i):
i = j
if i >= 0:
text = text[:i]
# Now shorten the text
while len(text) > 70 and p > 60:
# Cut off 10 chars
text = "..." + text[10:]
p = p - 7
# Now print the string, along with an indicator
print >> error_message, '> ', text.replace('\t', ' ').encode(sys.getdefaultencoding())
print >> error_message, '> ', ' '*p + '^'
print >> error_message, 'List of nearby tokens:', scanner
return error_message.getvalue()
開發者ID:youtube,項目名稱:spitfire,代碼行數:41,
示例19: getCurrentWord
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def getCurrentWord(self, entry):
i = entry.get_point()
text = entry.get_chars(0,-1)
word = re.split(r'\s', text)[-1]
start = string.rfind(text, word)
end = start+len(word)
return (word, (start, end))
開發者ID:kenorb-contrib,項目名稱:BitTorrent,代碼行數:9,
示例20: isCursorOnLastLine
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def isCursorOnLastLine(entry):
if entry.get_point() >= string.rfind(string.rstrip(entry.get_chars(0,-1)), '\n'):
return 1
開發者ID:kenorb-contrib,項目名稱:BitTorrent,代碼行數:5,
示例21: __get_background_url
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def __get_background_url(self, url):
# background-image: url('http://img.178.com/dota2/201511/241827471049/241827723987.jpg');
start_index = string.find(url, "'")
end_index = string.rfind(url, "'")
return url[start_index + 1:end_index]
開發者ID:uin3566,項目名稱:Dota2Server,代碼行數:7,
示例22: printInputFiles
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def printInputFiles(self):
"""
Make the input file(s) associated with this object
"""
# replaced find with rfind to located the rightmost '.'
# ... in order to fix bug with dealing with.blender directory
# ... mike pan
period = string.rfind(self.pqrpath,".")
if self.asyncflag == 1:
outname = self.pqrpath[0:period] + "-para.in"
# Temporarily disable async flag
for elec in self.elecs:
elec.asyncflag = 0
file = open(outname, "w")
file.write(str(self))
file.close()
# Now make the async files
elec = self.elecs[0]
nproc = elec.pdime[0] * elec.pdime[1] * elec.pdime[2]
for i in range(int(nproc)):
outname = self.pqrpath[0:period] + "-PE%i.in" % i
for elec in self.elecs:
elec.asyncflag = 1
elec.async = i
file = open(outname, "w")
file.write(str(self))
file.close()
else:
if period > 0:
outname = self.pqrpath[0:period] + ".in"
else:
outname = self.pqrpath + ".in"
file = open(outname, "w")
file.write(str(self))
file.close()
開發者ID:MonZop,項目名稱:BioBlender,代碼行數:43,
示例23: dumpPickle
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def dumpPickle(self):
"""
Make a Python pickle associated with the APBS input parameters
"""
period = string.rfind(self.pqrpath,".")
# mike pan
if period > 0:
outname = self.pqrpath[0:period] + "-input.p"
else:
outname = self.pqrpath + "-input.p"
pfile = open(outname, "w")
pickle.dump(self, pfile)
pfile.close()
開發者ID:MonZop,項目名稱:BioBlender,代碼行數:16,
示例24: process
點讚 5
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def process(filename, size=-1):
file = out_dir + filename
if path.isfile(file) and stat(file).st_size == size:
print 'Skipping: ' + filename
return
print 'Processing: ' + filename
handle = urlopen(base_url + filename)
headers = handle.info()
content_length = int(headers.getheader('Content-Length'))
last_modified = mktime(strptime(headers.getheader('Last-Modified'), '%a, %d %b %Y %H:%M:%S %Z'))
if rfind(filename, '/') > 0:
dir = out_dir + filename[:rfind(filename, '/')]
else:
dir = out_dir
if not path.isdir(dir):
print 'Creating ' + dir
makedirs(dir)
if not path.isfile(file):
download(filename, last_modified)
else:
file_stat = stat(file)
if file_stat.st_mtime != last_modified or file_stat.st_size != content_length:
download(filename, last_modified)
else:
print 'Skipping: ' + filename
開發者ID:opencas,項目名稱:mirrord,代碼行數:31,
示例25: upload
點讚 4
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def upload (self, source, target, flags) :
'''Uploads a file from the LOCAL, PHYSICAL filesystem to
the replica management system.
@param source: URL (should be file:// or local path) of local file
@param target: Optional param containing ?resource=myresource query
This will upload the file to a specified iRODS
resource or group.
'''
#TODO: Make sure that the source URL is a local/file:// URL
complete_path = saga.Url(source).get_path()
# extract the path from the LogicalFile object, excluding
# the filename
destination_path=self._url.get_path()[0:string.rfind(
self._url.get_path(), "/")+1]
try:
#var to hold our command result, placed here to keep in scope
returncode = out = 0
# note we're uploading
self._logger.debug("Beginning upload operation " +\
"will register file in logical dir: %s" %
destination_path)
# the query holds our target resource
query = saga.Url(target).get_query()
# list of args we will generate
arg_list = ""
# parse flags + generate args
if flags:
if flags & saga.namespace.OVERWRITE:
arg_list += "-f "
# was no resource selected?
if query==None:
self._logger.debug("Attempting to upload to default resource")
returncode, out, _ = self.shell.run_sync("iput %s %s %s" %
(arg_list, complete_path, destination_path))
# resource was selected, have to parse it and supply to iput -R
else:
#TODO: Verify correctness
resource = query.split("=")[1]
self._logger.debug("Attempting to upload to query-specified resource %s" % resource)
returncode, out, _ = self.shell.run_sync("iput -R %s %s %s %s" %
(resource, arg_list, complete_path, destination_path))
# check our result
if returncode != 0:
raise saga.NoSuccess ("Could not upload file %s, errorcode %s: %s"\
% (complete_path, str(returncode),
out))
except Exception, ex:
# couldn't upload for unspecificed reason
raise saga.NoSuccess._log (self._logger, "Couldn't upload file: %s" % ex)
開發者ID:PanDAWMS,項目名稱:pilot,代碼行數:62,
示例26: __init__
點讚 4
# 需要導入模塊: import string [as 別名]
# 或者: from string import rfind [as 別名]
def __init__(self, pqrpath, size, method, asyncflag, istrng=0, potdx=0):
"""
Initialize the input file class. Each input file contains
a PQR name, a list of elec objects, and a list of strings
containing print statements. For starters assume two
ELEC statements are needed, one for the inhomgenous and
the other for the homogenous dielectric calculations.
Users can edit the elec statements and the print statements.
This assumes you have already run psize, either by
size.runPsize(/path/to/pqr) or
size.parseString(string)
size.setAll()
Parameters
pqrpath: The path to the PQR file (string)
size: The Psize object (psize)
method: The method (para, auto, manual, async) to use
asyncflag: 1 if async is desired, 0 otherwise
"""
self.pqrpath = pqrpath
self.asyncflag = asyncflag
# Initialize variables to default elec values
elec1 = Elec(pqrpath, size, method, asyncflag, istrng, potdx)
if potdx == 0:
elec2 = Elec(pqrpath, size, method, asyncflag, istrng, potdx)
setattr(elec2, "sdie", 2.0)
setattr(elec2, "write", [])
else:
elec2 = ""
self.elecs = [elec1, elec2]
i = string.rfind(pqrpath, "/") + 1
self.pqrname = pqrpath[i:]
if potdx == 0:
self.prints = ["print elecEnergy 2 - 1 end"]
else:
self.prints = []
開發者ID:MonZop,項目名稱:BioBlender,代碼行數:46,
注:本文中的string.rfind方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。
转载地址:http://cftnx.baihongyu.com/