[英]How to find find a grouping of upper and lower case characters in a string in python 3
我正在研究Python挑戰,而我正在研究的級別要求我們找到一個小寫字母,兩邊恰好由三個大寫字母包圍。 我編寫了以下代碼,這看起來很粗糙,但我認為應該可以。 但是,我得到的只是一個空字符串。
source="Hello there" #the string I have to work with
key=""#where I want to put the characters that fit
for i in source:
if i==i.lower(): # if it's uppercase
x=source.index(i) #makes number that's the index of i
if source[x-1].upper()==source[x-1] and source[x-2]==source[x-2].upper() and source[x-3].upper()==source[x-3]: #checks that the three numbers before it are upper case
if source[x+1].upper()==source[x+1] and source[x+2].upper()==source[x+2] and source[x+3].upper()==source[x+3]: #checks three numbers after are uppercase
if source[x+4].lower()==source[x=4] and source[x-4].lower()==source[x-4]: #checks that the fourth numbers are lowercase
key+=i #adds the character to key
print(key)
我知道這真的很亂,但是我不明白為什么它只返回一個空字符串。 如果您有任何疑問,或者有更有效的方法,我將不勝感激。 謝謝
使用正則表達式可以輕松得多。
re.findall(r'(?<![A-Z])[A-Z]{3}([a-z])(?=[A-Z]{3}(?:\Z|[^A-Z]))', text)
運作方式如下:
(?<![AZ])
是一個否定的后置斷言 ,可確保我們前面沒有大寫字母。
[AZ]{3}
是三個大寫字母。
([az])
是我們要查找的小寫字母。
(?=[AZ]{3}(?:\\Z|[^AZ]))
是一個前瞻性斷言 ,可確保我們后面跟隨三個大寫字母,而不是四個大寫字母。
您可能需要根據實際要更改的內容來更改分組。 查找小寫字母。
我建議使用帶有keyfunc
的itertools.groupby
方法來區分小寫字母和大寫字母。
首先,您需要一個輔助函數來重構檢查邏輯:
def check(subseq):
return (subseq[0][0] and len(subseq[0][1]) == 3
and len(subseq[1][1]) == 1
and len(subseq[2][1]) == 3)
然后分組並檢查:
def findNeedle(mystr):
seq = [(k,list(g)) for k,g in groupby(mystr, str.isupper)]
for i in range(len(seq) - 2):
if check(seq[i:i+3]):
return seq[i+1][1][0]
在解釋器中檢查seq
以了解其工作原理,這應該非常清楚。
編輯:一些錯字,我沒有測試代碼。
現在進行測試:
>>> findNeedle("Hello there HELxOTHere")
'x'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.