本文整理汇总了Python中string.index函数的典型用法代码示例。如果您正苦于以下问题:Python index函数的具体用法?Python index怎么用?Python index使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了index函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: crypt
def crypt(self, plain):
"""Doesn't really encrypt, but rotates 13 chars through the alphabet"""
lowerA = "abcdefghijklmnopqrstuvwxyz"
lowerB = "nopqrstuvwxyzabcdefghijklm"
upperA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
upperB = "NOPQRSTUVWXYZABCDEFGHIJKLM"
digitA = "0123456789"
digitB = "5678901234"
res = ""
import string
for char in plain:
if char in lowerA:
res = res + lowerB[string.index(lowerA, char)]
elif char in upperA:
res = res + upperB[string.index(upperA, char)]
elif char in digitA:
res = res + digitB[string.index(digitA, char)]
else:
res = res + char
return res
开发者ID:elmore,项目名称:sixthdev,代码行数:26,代码来源:Rot13Password.py
示例2: one_word
def one_word(line):
try:
string.index(line," ")
return False
except ValueError:
return True
开发者ID:egreif1,项目名称:PHelpers,代码行数:7,代码来源:text.py
示例3: _run
def _run(self):
for filename, file_data in self.files.items():
try:
contents = file_data['_contents']
except KeyError:
continue
if contents.startswith('{{{\n'):
try:
end_pos = string.index(contents, '\n}}}')
except ValueError:
continue
file_data.update(json.loads('{' + contents[:end_pos + 4].strip().lstrip('{').rstrip('}') + '}'))
contents = contents[end_pos + 4:]
self.mark_matched(filename)
elif contents.startswith('---\n'):
try:
end_pos = string.index(contents, '\n---')
except ValueError:
continue
file_data.update(yaml.load(contents[:end_pos]))
contents = contents[end_pos + 4:]
self.mark_matched(filename)
file_data['_contents'] = contents
开发者ID:BasementCat,项目名称:breeze,代码行数:26,代码来源:plugins.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: __init__
def __init__(self, pos, offset, line):
"""Initialize the synset from a line off a WN synset file."""
self.pos = pos
"part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB."
self.offset = offset
"""integer offset into the part-of-speech file. Together
with pos, this can be used as a unique id."""
tokens = string.split(line[:string.index(line, '|')])
self.ssType = tokens[2]
self.gloss = string.strip(line[string.index(line, '|') + 1:])
self.lexname = Lexname.lexnames and Lexname.lexnames[
int(tokens[1])] or []
(self._senseTuples, remainder) = _partition(
tokens[4:], 2, int(tokens[3], 16))
(self._pointerTuples, remainder) = _partition(
remainder[1:], 4, int(remainder[0]))
if pos == VERB:
(vfTuples, remainder) = _partition(
remainder[1:], 3, int(remainder[0]))
def extractVerbFrames(index, vfTuples):
return tuple(map(lambda t: int(t[1]), filter(lambda t, i=index: int(t[2], 16) in (0, i), vfTuples)))
senseVerbFrames = []
for index in range(1, len(self._senseTuples) + 1):
senseVerbFrames.append(extractVerbFrames(index, vfTuples))
self._senseVerbFrames = senseVerbFrames
self.verbFrames = tuple(extractVerbFrames(None, vfTuples))
"""A sequence of integers that index into
开发者ID:pattern3,项目名称:pattern,代码行数:28,代码来源:wordnet.py
示例6: GetParameters
def GetParameters(self):
"""
Collects every member of every section object and filters out those that are not parameters of
the model. The function will collect:
* every parameter of the the mechanisms
* every mechanism
* some default parameters that are always included in a model,
and pointprocesses that are not some sort of Clamp
:return: the filtered content of the model in a string matrix
"""
matrix=[]
temp=[]
temp2=""
temp3=""
for sec in self.hoc_obj.allsec():
temp.append(str(self.hoc_obj.secname()))
defaults="L"+", cm"+", Ra"+", diam"+", nseg"
for n in ["ena","ek","eca"]:
try:
index(dir(self.hoc_obj),n)
defaults+=", "+n
except ValueError:
continue
for n in sec(0.5).point_processes():
try:
index(n.hname(),"Clamp")
continue
except ValueError:
not_param=set(['Section', '__call__', '__class__', '__delattr__',
'__delitem__', '__doc__', '__format__', '__getattribute__',
'__getitem__', '__hash__', '__init__', '__iter__',
'__len__', '__new__', '__nonzero__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__',
'allsec', 'amp', 'baseattr', 'cas',
'delay', 'dur', 'get_loc', 'has_loc',
'hname', 'hocobjptr', 'i',
'loc', 'next', 'ref', 'setpointer'])
defaults+=", "+", ".join(list(set(dir(n)).difference(not_param)))
temp.append(defaults)
for seg in sec:
for mech in seg:
#print dir(mech)
temp2=temp2+" "+str(mech.name())
if self.contains(dir(mech),str(mech.name()))!="":
temp3=temp3+self.contains(dir(mech),str(mech.name()))+" "
temp.append( temp3 )
temp.append(temp2)
matrix.append(temp)
temp2=""
temp3=""
temp=[]
break
return matrix
开发者ID:LibreChou,项目名称:optimizer,代码行数:60,代码来源:modelHandler.py
示例7: ParseAddTests
def ParseAddTests(cmakefile):
resp = []
ifstream = open(cmakefile)
lines = ifstream.readlines()
ifstream.close()
current_test_cmake_code = []
current_test_name = ""
in_addtest = False
for line in lines:
if line.count("add_test"):
in_addtest = True
try:
start = string.index(line,"add_test")
end = string.index(line," ",start)
current_test_name = line[start+9:end]
except ValueError:
try:
start = string.index(line,"add_test")
current_test_name = line[start+9:]
except ValueError:
pass
if in_addtest:
current_test_cmake_code.append(line)
if line.count(")"):
if in_addtest:
current_test_name.strip()
resp.append((current_test_name, current_test_cmake_code))
in_addtest = False
current_test_cmake_code = []
current_test_name = ""
return resp
开发者ID:kalxas,项目名称:OTB-DevUtils,代码行数:34,代码来源:codeParser.py
示例8: signupSuccess
def signupSuccess (request, userID):
model = object()
context = {}
useremail = ""
username = ""
user_type_initial = userID[-1]
if user_type_initial == 'c':
model = Customers
elif user_type_initial == 't':
model = Tradesman
new_user = get_object_or_404(model, userID = userID)
if user_type_initial == "c":
useremail = new_user.customer.email
username = new_user.customer.first_name
else:
useremail = new_user.user.email
username = new_user.user.first_name
emailprovider = useremail[string.index(useremail, "@") + 1 : string.index(useremail,".")]
context['username'] = username
context['emailprovider'] = emailprovider
context['useremail'] = useremail
# new_user = get_object_or_404(Tradesman, userID = userID)
# useremail = new_user.customer.email
# emailprovider = useremail[string.index(useremail, "@") + 1 : string.index(useremail,".")]
# context = {}
# context['username'] = new_user.customer.first_name
# context['emailprovider'] = emailprovider
# context['useremail'] = new_user.customer.email
return render(request, 'fixit/main/registration_success.html', context)
开发者ID:EzechukwuJI,项目名称:fixit,代码行数:31,代码来源:views.py
示例9: IDtoURL
def IDtoURL(id):
"""Convert an authorization or notification ID from address to URL format
Example: "[email protected]" becomes
"http://example.org/notify/54DC1B81-1729-4396-BA15-AFE6B5068E32"
"""
return "http://"+ id[string.index(id, "@")+1:] + "/notify/" + id[0:string.index(id, "@")] # TODO: Will need to change to https://
开发者ID:jimfenton,项目名称:notif-notifier,代码行数:7,代码来源:notify.py
示例10: rename
def rename(source, dest):
"""
Renames files specified by UNIX inpattern to those specified by UNIX
outpattern. Can only handle a single '*' in the two patterns!!!
Usage: rename (source, dest) e.g., rename('*.txt', '*.c')
"""
infiles = glob.glob(source)
outfiles = []
incutindex = string.index(source, "*")
outcutindex = string.index(source, "*")
findpattern1 = source[0:incutindex]
findpattern2 = source[incutindex + 1 :]
replpattern1 = dest[0:incutindex]
replpattern2 = dest[incutindex + 1 :]
for fname in infiles:
if incutindex > 0:
newname = re.sub(findpattern1, replpattern1, fname, 1)
if outcutindex < len(dest) - 1:
if incutindex > 0:
lastone = string.rfind(newname, replpattern2)
newname = newname[0:lastone] + re.sub(findpattern2, replpattern2, fname[lastone:], 1)
else:
lastone = string.rfind(fname, findpattern2)
if lastone <> -1:
newname = fname[0:lastone]
newname = newname + re.sub(findpattern2, replpattern2, fname[lastone:], 1)
print fname, newname
os.rename(fname, newname)
return
开发者ID:eddienko,项目名称:SamPy,代码行数:30,代码来源:io.py
示例11: replaceChar
def replaceChar(strEURL):
"""
replace CHAR() with character
"""
if 'CHAR(' in strEURL:
urllist = strEURL.split('CHAR(')
strReturnWithChars = ""
for s in urllist:
strTmpPart = ""
if ")" in s or 'CHAR(' in s:
if len(s) > string.index(s, ')') + 1:
tmpChrCode = s[:string.index(s, ')')]
if tmpChrCode.isdigit():
if int(s[:string.index(s, ')')]) < 257:
seq = (strReturnWithChars, chr(int(s[:string.index(s, ')')])),s[string.index(s, ')') +1 -len(s):])
strReturnWithChars = strTmpPart.join( seq )
else:
print (s[:string.index(s, ')')] + " is not a valid char number")
seq = (strReturnWithChars, s )
strReturnWithChars = strTmpPart.join(seq )
else:
print ('error parsing text. Char code is not numeric')
print s
else:
seq = (strReturnWithChars, s )
strReturnWithChars = strTmpPart.join(seq )
else:
seq = (strReturnWithChars, s )
strReturnWithChars = strTmpPart.join(seq )
else:
strReturnWithChars = strEURL
return strReturnWithChars
开发者ID:RandomRhythm,项目名称:Web-Log-Deobfuscate,代码行数:33,代码来源:Deobfuscate_Web_Log.py
示例12: encode
def encode(self):
s = self.validated
if self.checksum == -1:
if len(s) <= 10:
self.checksum = 1
else:
self.checksum = 2
if self.checksum > 0:
# compute first checksum
i = 0; v = 1; c = 0
while i < len(s):
c = c + v * string.index(self.chars, s[-(i+1)])
i = i + 1; v = v + 1
if v > 10:
v = 1
s = s + self.chars[c % 11]
if self.checksum > 1:
# compute second checksum
i = 0; v = 1; c = 0
while i < len(s):
c = c + v * string.index(self.chars, s[-(i+1)])
i = i + 1; v = v + 1
if v > 9:
v = 1
s = s + self.chars[c % 10]
self.encoded = 'S' + s + 'S'
开发者ID:pacoqueen,项目名称:ginn,代码行数:30,代码来源:common.py
示例13: __init__
def __init__(self, inf):
R = string.split(inf.read(), "\n")
self.preamble = [ ]
self.globalFuncs = globalFuncs = [ ]
self.parFlag = 0
i = 0
while i < len(R):
x = R[i]
# find functions and consume them
got_it = 0
if self.parOnRe.search(x):
self.parFlag = 1
elif self.parOffRe.search(x):
self.parFlag = 0
elif self.parFlag and self.globalDeclRe.search(x):
try:
string.index(x, "(")
isAFunc = 1
except ValueError:
isAFunc = 0
if isAFunc:
f = Function(x)
globalFuncs.append(f)
i = i + 1 + f.read(R[i+1:])
got_it = 1
if not got_it:
# anything else is preamble
self.preamble.append(x)
i = i + 1
开发者ID:ChrisX34,项目名称:stuff,代码行数:29,代码来源:mmt.py
示例14: getText
def getText(string = None):
if string != None:
try:
closeBkt = string.index('>') + len('>')
openBkt = string.index('<', closeBkt)
return string[closeBkt:openBkt]
except ValueError:
return ""
开发者ID:charounsons,项目名称:myCrawlingBaby,代码行数:8,代码来源:crawl2.py
示例15: strip_address
def strip_address(address):
"""
Strip the leading & trailing <> from an address. Handy for
getting FROM: addresses.
"""
start = string.index(address, '<') + 1
end = string.index(address, '>')
return address[start:end]
开发者ID:exocad,项目名称:exotrac,代码行数:8,代码来源:notification.py
示例16: testGenerateStanzaWildCard
def testGenerateStanzaWildCard(self):
a = SourceSet(set(['foo.c']),
set([SourceListCondition('x64', 'Chromium', '*')]))
stanza = a.GenerateGnStanza()
string.index(stanza, '== "x64"')
string.index(stanza, 'ffmpeg_branding == "Chromium"')
# OS is wild-card, so it should not be mentioned in the stanza.
self.assertEqual(-1, string.find(stanza, 'OS =='))
开发者ID:freeors,项目名称:SDL,代码行数:8,代码来源:generate_gn_unittest.py
示例17: parse_timestamp
def parse_timestamp(self, event, line):
start = string.index(line, "[")
end = string.index(line, "]")
if end - start < 20:
raise Exception("Incorrect [date_time] field found in " + line)
event.now = line[start + 1:end]
line = line[end+1:].strip()
return line
开发者ID:yorp-me,项目名称:qlproxy_external,代码行数:9,代码来源:import.py
示例18: expandvars
def expandvars(path):
"""Expand paths containing shell variable substitutions.
The following rules apply:
- no expansion within single quotes
- no escape character, except for '$$' which is translated into '$'
- ${varname} is accepted.
- varnames can be made out of letters, digits and the character '_'"""
# XXX With COMMAND.COM you can use any characters in a variable name,
# XXX except '^|<>='.
if '$' not in path:
return path
res = ''
index = 0
pathlen = len(path)
while index < pathlen:
c = path[index]
if c == '\'': # no expansion within single quotes
path = path[index + 1:]
pathlen = len(path)
try:
index = string.index(path, '\'')
res = res + '\'' + path[:index + 1]
except string.index_error:
res = res + path
index = pathlen -1
elif c == '$': # variable or '$$'
if path[index + 1:index + 2] == '$':
res = res + c
index = index + 1
elif path[index + 1:index + 2] == '{':
path = path[index+2:]
pathlen = len(path)
try:
index = string.index(path, '}')
var = path[:index]
if os.environ.has_key(var):
res = res + os.environ[var]
except string.index_error:
res = res + path
index = pathlen - 1
else:
var = ''
index = index + 1
c = path[index:index + 1]
while c != '' and c in varchars:
var = var + c
index = index + 1
c = path[index:index + 1]
if os.environ.has_key(var):
res = res + os.environ[var]
if c != '':
res = res + c
else:
res = res + c
index = index + 1
return res
开发者ID:asottile,项目名称:ancient-pythons,代码行数:57,代码来源:dospath.py
示例19: getCollaborators
def getCollaborators( rawWikiText, lang ):
"""
return a list of tuple with ( user, value ), where user is the name of user
that put a message on the page, and the value is the number of times that
he appear in rawText passed.
parameter:
lang: lang of wiki [it|nap|vec|en|la]
rawWikiText: text in wiki format (normally discussion in wiki)
"""
import re
resname = []
start = 0
search = '[['+i18n[lang][1]+":"
searchEn = '[['+i18n['en'][1]+":"
io = len(search)
while True:
#search next user
try:
iu = index( rawWikiText, search, start ) #index of username
except ValueError:
if search == searchEn:
break
# now search for English signatures
search = searchEn
start = 0
io = len(search)
continue
#begin of the username
start = iu + io
#find end of username with regex
username = re.findall( "[^]|&/]+",rawWikiText[start:] )[0]
if username == '' or username == None:
print "Damn! I cannot be able to find the name!"
print "This is the raw text:"
print rawWikiText[start:start+30]
print "What is the end character? (all the character before first were ignored)"
newdelimiter = sys.stdin.readline().strip()[0]
try:
end.append( index( rawWikiText, newdelimiter, start ) )
except ValueError:
print "Damn! you give me a wrong character!.."
exit(0)
resname.append( username ) # list of all usernames (possibly more than one times for one)
start += len(username) + 1 # not consider the end character
#return a list of tuple, the second value of tuple is the weight
return weight( resname )
开发者ID:SuperbBob,项目名称:trust-metrics,代码行数:57,代码来源:wikixml2graph.py
示例20: split_to
def split_to(address):
"""
Return 'address' as undressed (host, fulladdress) tuple.
Handy for use with TO: addresses.
"""
start = string.index(address, '<') + 1
sep = string.index(address, '@') + 1
end = string.index(address, '>')
return address[sep:end], address[start:end]
开发者ID:exocad,项目名称:exotrac,代码行数:9,代码来源:notification.py
注:本文中的string.index函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论