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