如何在 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)

以下是它的工作原理:

  • (?<![A-Z])是一个负面的回溯断言,它确保我们前面没有大写字母。

  • [A-Z]{3}是三个大写字母。

  • ([a-z])是我们正在寻找的小写字母。

  • (?=[A-Z]{3}(?:Z|[^A-Z]))是一个前瞻性断言,确保我们后面跟着三个大写字母,而不是四个。

您可能需要根据实际要查找的内容更改分组。 这将找到小写字母。

我建议使用带有keyfuncitertools.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'

最新更新