2014-12-06 220 views
0
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') 

如何讓循環再次啓動並保持跟蹤值iWhile循環與if語句

+3

任何不使用'subword in word'和'word.index(subword)'的理由? – 2014-12-06 14:08:18

+2

你是什麼意思「跟蹤'我'」? – rlms 2014-12-06 14:10:48

+0

因此,當循環繼續時,由於if語句的原因,它保持離開它的點。 – chubaka 2014-12-06 14:13:47

回答

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] 
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 

你不能跳轉或跳躍的循環方面。你需要使用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)))