Python i';I’’我试着用我自己的原创方式制作一个反元音的程序,但由于某种原因,一个元音会使程序失败
所以基本上我应该传递一个字符串作为参数,prog应该把一个字符一个字符放到一个空列表中,检查每个字符与字符串“aeiouAEIOU”的比较,如果比较的字符包含任何“aeiouAEIOU”,那么它应该删除它。Python i';I’’我试着用我自己的原创方式制作一个反元音的程序,但由于某种原因,一个元音会使程序失败,python,Python,所以基本上我应该传递一个字符串作为参数,prog应该把一个字符一个字符放到一个空列表中,检查每个字符与字符串“aeiouAEIOU”的比较,如果比较的字符包含任何“aeiouAEIOU”,那么它应该删除它。 然后,我将元素添加到一个空字符串中,并打印出无元音字符串,当您在列表上迭代时,从列表中删除元素并不能像您预期的那样工作。在迭代列表时不要修改它。以下是问题代码: def anti_vowel(text): empL = [] #just an empty list index
然后,我将元素添加到一个空字符串中,并打印出无元音字符串,当您在列表上迭代时,从列表中删除元素并不能像您预期的那样工作。在迭代列表时不要修改它。以下是问题代码:
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)
在迭代时缩短列表会跳过列表中的其他字符
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'
希望这有帮助所以你应该从字符串中删除元音?描述输入、预期输出和实际输出。
'.join([c代表c在文本中,如果c.lower()不在'aeiou'中])
@PatrickHaugh-Nice——这对于有经验的Python用户来说很容易理解。不过,这看起来是个家庭作业,不是家庭作业,我在代码学院做python部分!但是我在任何地方看到的解决方案都与您提供的类似,我试图以我自己的方式实现它。看来我想的不可能了谢谢你们的帮助@PatrickHaughthanks似乎忽略了迭代的细节@MarkTolonen@franny迭代原始文本并将非元音添加到新字符串中,而不是迭代列表并删除字符。那么您就不会修改迭代器。此外,通过投票和接受答案来表达谢意:)
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']]))