Python:尝试比较索引处的两个字符串时列出索引超出范围?

标签 python string

我有这个函数来检查字符串是否包含三个或更多小写字母。

def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
i = 0
flag = 0
while i <= len(word):
    j = 0
    while j <= len(lowCharList):
        if lowCharList[j] == word[i]:
            flag += 1
            j = 0
        else:
            j += 1
    i += 1
if flag >= 3:
    return True

简单来说,我传入一个字符串(单词)并创建可接受的字符列表(lowCharList)。

然后,我设置了一个嵌套的 while 循环来检查 lowCharList 的每个索引处的 word[i],直到找到匹配项。

然后它重置 lowCharList 计数器并将标志加 1,然后移至 word[i+1]。

如果到达 z 时未找到匹配项,则无论如何都会移至 word[i+1]。

出于某种原因,为什么我在主函数中尝试示例输入。

def main():
  word = 'corRe!33'
  print(lowerCaseValid(word))

我收到此错误:

in lowerCaseValid
if lowCharList[j] == word[i]:
IndexError: list index out of range

为什么会抛出这个错误?谢谢。

最佳答案

using python's in operator is easier...

    def lowerCaseValid(word):
       cnt = 0
       lowCharList = ['abcdefghijklmnopqrstuvwxyz']
       chars = lowCharList.pop ()
       for ch in word:
           if ch in chars:
           cnt += 1

       return  cnt >= 3

or with using sets just 2 lines of code

def lowerCaseValid(word):

    lowCharList = ['abcdefghijklmnopqrstuvwxyz']

    return len(set(lowCharList.pop()) & set(word)) >=3

or one liner with map and lambda

def lowerCaseValid(word):

    return len(list(map(lambda x: x.islower, list(word)))) >=3

关于Python:尝试比较索引处的两个字符串时列出索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978412/

相关文章:

string - 从 std::string 转换为 String^

Python:忽略 xml.etree.ElementTree 中的 namespace ?

python - 如何使用 NLTK ne_chunk 提取 GPE(位置)?

C 中用指针改变字符串的值

java - 使用散列法查找总长度最小的字符串子数组,该子数组包含原始数组中的所有不同字符串

php - 正则表达式从第一个大写匹配到查询字符串的句子结尾

c# - 正则表达式应用 - 匹配百分比

python - 我不知道为什么我得到一个空白的输出文件

python - "No module named ' cv2 ' "但已安装

python - 重新搜索()。TypeError : cannot use a string pattern on a bytes-like object