Python - 嵌套循环

时间:2015-06-23 07:30:25

标签: python

任何人都可以帮助我理解为什么我总是会收到错误 关于"索引越界"?

问题是获得刺痛并移除元音并在没有元音的情况下获取新字符串

代码:

def disemvowel(string):
    vowel=['E','A','I','O','U','Y','e','a','i','o','u','y']
    string = list(string)
    lenString = len(string)
    print (lenString)
    for i in range(0, lenString):
        for j in range(0, 12):
            if (string[i] == vowel[j]):
                print ("matched")
                del string[i]
    string = ''.join(string)
    print (string)
    return string

3 个答案:

答案 0 :(得分:2)

更多pythonic,请使用set代替@smci建议:

def disemvowel(s):
    vowel = {'E', 'A', 'I', 'O', 'U', 'Y', 'e', 'a', 'i', 'o', 'u', 'y'}
    return ''.join((char for char in s if char not in vowel))

答案 1 :(得分:0)

而不是删除构造新字符串

def disemvowel(string):
    vowel=['E','A','I','O','U','Y','e','a','i','o','u','y']
    string = list(string)
    final_string = []
    lenString = len(string)
    print (lenString)
    for i in range(0, lenString):
        for j in range(0, 12):
            if (string[i] == vowel[j]):
                print ("matched")
                final_string += string[i]
    string = ''.join(final_string)
    print (final_string)
    return final_string

答案 2 :(得分:0)

您还可以查看字符串库中的translate函数:

import string

def disemvowel(s):
    return string.translate(s, string.maketrans("",""), "EAIOUYeaiouy")

print disemvowel("Hello World")
  

Hll Wrld