如何检查辅音-元音模式的完整字符串并返回布尔值?

2024-07-05 14:40:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个项目,需要我检查一个编码引脚必须有这样的模式:辅音,元音。例如,3464140是bomelela

我以前试过这个:

def checkString(st):
    if st == '':
        return False
    elif st[0] in consonants and st[1] in vowels:
        return True
    else:
        return False

但是字符串长度可能会有所不同,所以我不太确定如何检查整个字符串

此函数应返回布尔值。我想我很接近了,但是我不知道如何返回真或假,因为我的if语句以I+1结尾

到目前为止,我有:

consonants = "bcdfghjklmnpqrstvwyz"
vowels = "aeiou"

def checkString(st):
  for i in range(len(st)):
    if i % 2 == 0:
      if st[i] in consonants:
         i + 1
    elif i % 2 != 0:
      if st[1] in vowels:
         i + 1

提前感谢,对于任何格式问题,我深表歉意,这是我的第一篇文章


Tags: 项目字符串infalse编码returnifdef
3条回答
def checkString(teststring):
    '''To check for pattern: Consonant:Vowel and return true if pattern exists'''
    const = "bcdfghjklmnpqrstvwyz"
    vowels = "aeiou"
    t_odd = teststring[::2].lower()
    t_even = teststring[1::2].lower()
    outcome = ["True" if x in const else "False" for x in t_odd ] + ["True" if y in vowels else "False" for y in t_even]
    return all(item == "True" for item in outcome)

#Test
checkString("Bolelaaa")
checkString("bomelela")

在这个函数中,我使用列表理解来测试odd&;偶数字母分别对应辅音和元音列表。如果所有比较都为true,则函数返回true

我们可以在特定的位置检查辅音或元音中的特定字符串,并在当前迭代中条件求值为真时继续下一次迭代

如果任何条件在任何迭代中失败,它将返回false。如果条件对所有迭代的计算结果都为True,那么函数最终将返回True

consonants = "bcdfghjklmnpqrstvwyz"
vowels = "aeiou"

def checkString(st):
    for i in range(len(st)):
        if i % 2 == 0 and st[i] in consonants:
            continue
        elif i % 2 != 0 and st[i] in vowels:
            continue
        else: 
            return False 

    return True

这些简单的更改可以为您实现以下目的:

consonants = "bcdfghjklmnpqrstvwyz"
vowels = "aeiou"


def checkString(st):
    for i in range(len(st)):
        if i % 2 == 0:
            if st[i] not in consonants:
                return False
        else:
            if st[i] not in vowels:
                return False
    return True

相关问题 更多 >