def subStringMatchExact(word,subword):
if len(word)<len(subword):
print 'substring is bigget than the string, please type another substring.'
return None
else:
for i in xrange(0,len(word)):
t = ()
j = 0
while word[i] == subword[j]:
j = j+1
i = i+1
if j == len(subword):
t = t+(i-j,)
return t
print subStringMatchExact('afgbcdefg', 'fg')
如何让循环重新开始并跟踪i
的值?
答案 0 :(得分:0)
您没有指定要再次运行哪个循环,但是在结束后执行该循环的唯一方法是将其放在另一个循环中。您可以通过将其存储在for循环范围之外的另一个变量中来跟踪i。 像这样:
def subStringMatchExact(word,subword):
if len(word)<len(subword):
print 'substring is bigger than the string, please type another substring.'
return None
else:
lasti=0 # <- lasti is outside the scope of the for loop
# So it will save the value even after the for loop terminates
for i in xrange(0,len(word)):
t = []
j = 0
lasti=i # assigning i to lasti
while word[i] == subword[j]:
j = j+1
i = i+1
if j == len(subword):
t = t+(i-j,)
return t
如果您试图获取子字的起始位置和结束位置,则可以执行此操作:
def subStringMatchExact(word,subword):
if len(word)<len(subword):
print 'substring is bigger than the string, please type another substring.'
return None
else:
start, end = -1, -1
for i in range(0,len(word)):
for j in range(0,len(subword)):
if word[i] == subword[j]:
if start == -1:
start = i
end = (j+i-1)
return [start,end]
答案 1 :(得分:0)
如果您正在尝试即兴创建代码以从字符串匹配错误的地方继续,那么For
循环就不是了。这将有所帮助:
def subStringMatchExact(word,subword):
if len(word)<len(subword):
print 'substring is bigget than the string, please type another substring.'
return None
else:
i = 0
while i < len(word):
t = ()
j = 0
while word[i] == subword[j]:
j = j+1
i = i+1
if j == len(subword):
t = t+(i,)
return t
你不能在for循环方面跳跃或跳跃。你需要使用while循环。请注意,除了教育目的之外,不要走这条路。这可以使用字符串索引方法轻松完成:
def subStringMatchExact(word,subword):
if len(word) < len(subword):
print 'substring is bigger than the string, please type another substring.'
if subword in word:
word_index = word.index(subword)
return tuple(range(word_index, word_index+len(subword)))