2014-09-22 73 views
0

我试图解决pythonchallenge上的一个挑战..它给你一个带有不同情况的信件的文本墙,并且你试图找到被3个包围的小写字母从每边大写字母.. 这里是我的尝试通过字符串循环来检查特定的大小写匹配

text=open("challenge.txt") 
thedata=text.read() 

def check(s,c): 
    upper='ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
    lower="abcdefghijklmnopqrstuvwxyz" 
    n=s.index(c) 
    if (c in lower) and (s[n-2] in upper) and (s[n+1] in upper) and (s[n-1] in upper) and (s[n+2] in upper) and (s[n-3] in upper) and (s[n+3] in upper): 
     return True 
    else: 
     return False 

def solver(s): 
    listOfSol=[] 
    for c in s: 
     try: 
      if check(s,c): 
       n=s.index(c) 
       entry= (s[n-3:n+4]) 
       if entry not in listOfS: 
        listOfSol.append(entry) 
     except KeyError: 
      continue 
    return listOfSol 

print solver(thedata) 

这是行不通的,我想知道为什么,请不要给我一个答案的快捷方式或尝试给我挑战的解决方案,因为我认为自己是一个Python初学者,我只想知道为什么这不起作用(总是返回一个空列表)。 由于事先

+0

如果字符串中每个字符有多个,该怎么办? “aBCDaBCD”.index(“a”)给出了什么? – jonrsharpe 2014-09-22 10:50:10

+0

哦,我没有想到这一点,谢谢jonsharpe ..我会试着用* enumerate(s)*来解决这个问题,并且看看会发生什么。 – 2014-09-22 11:33:49

回答

0

很抱歉,如果我已经解决了你太多,但你可以列举了数据,然后使用中的for循环的附加变量来跳过匹配等,以使字母:

for index, letter in enumerate(thedata): 
     #'add' is a number we're adding to the index that we want to check, so it can be incremented by 7 to skip matching strings 
     add = 0 
     index2 = index + add 

     #use a try-except clause because there is going to be indexerrors checking the end of the string 
     try: 
     #if statement goes here 
      #add to matches 
      add += 7 

     except: 
     continue 
相关问题