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初學者,我只想知道爲什麼這不起作用(總是返回一個空列表)。 由於事先
如果字符串中每個字符有多個,該怎麼辦? 「aBCDaBCD」.index(「a」)給出了什麼? – jonrsharpe 2014-09-22 10:50:10
哦,我沒有想到這一點,謝謝jonsharpe ..我會試着用* enumerate(s)*來解決這個問題,並且看看會發生什麼。 – 2014-09-22 11:33:49