我正在尝试以我自己的原始方式创建一个反元音程序,但由于某种原因,一个元音使程序失败


def anti_vowel(text):
    empL = [] #just an empty list
    index = 0 #just an index counter
    empS = "" #just an empty String
    for i in text: 
        empL.append(i) # in this loop ill be adding the str passed in by "text" char by char to the empty list 
    else:   # since this its a for/else loop this is also going to run
        for char in empL: # iterates to each element in the list  
            if char in "aeiouAEIOU": **# if the element thats being iterated at the moment is cotained in this string**
                empL.remove(char) #remove it
        else: #yes this is going to run because it's another for/else
            sizeEmpL = len(empL) # just the size of empty list
            while sizeEmpL != 0 :
                empS = empS + empL[index]
                print(empS)
                index += 1
                sizeEmpL -= 1
            print(empL)
            print(empS)

所以基本上我应该传递一个字符串作为参数,prog 应该将一个字符一个字符一个个放在一个空列表中,并检查每个字符与字符串"aeiouAEIOU"进行比较,如果比较的字符包含任何"aeiouAEIOU",那么它应该删除它。然后我将元素添加到空字符串并打印出元音字符串

在迭代列表时从列表中删除元素无法按预期工作。在循环访问列表时,不要修改列表。 这是问题代码:

for char in empL:
    if char in "aeiouAEIOU":
        empL.remove(char)

循环访问列表时缩短列表具有跳过列表中其他字符的效果。

string = 'ofiiajpfeiajpfeiaef   ijgapijfpij'
''.join([x for x in string if x not in ['a','e','i','o','u','A','E','I','O','U']])

输出:

'fjpfjpff   jgpjfpj'

你可以用它做一个函数:

def no_vowels(input_string):  
    return (''.join([x for x in input_string if x not in ['a','e','i','o','u','A','E','I','O','U']]))

希望有帮助

相关内容

最新更新