循环遍历字符串以检查特定的大小写匹配

时间:2014-09-22 10:24:13

标签: python-2.7

我正在尝试解决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初学者,我只是想知道为什么这不工作(总是返回一个空列表)。 提前谢谢

1 个答案:

答案 0 :(得分:0)

很抱歉,如果我为你解决了太多问题,但是你可以枚举数据,那么在for循环中使用一个add变量来跳过过去那些匹配的字母:

 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