我想删除python中单词的元音,

2024-07-03 07:59:34 发布

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

如果输入是'ameer bau',那么输出应该是'mr b',但是我得到了错误'index out of range'我的代码如下

str=input()
new=list(str)

for i in range(len(new)):
    if new[i]=='a' or new[i]=='e' or new[i]=='i' or new[i]=='o' or new[i]=='u':
        new.pop(i)

str1="".join(new)
print(str1)

Tags: orof代码newinputindex错误range
3条回答

for循环中,迭代new的索引,但是在循环体中{}被调用。这会改变列表的大小,最终导致IndexError。在

相反,请使用列表理解(如果需要列表)或生成器表达式:

string = input()
vowels = {'a', 'e', 'i', 'o', 'u'}
new_string = ''.join(x for x in string if x not in vowels)
print(new_string)

另一个选择是build a translation table,然后使用str.translate来丢弃元音:

remove_vowels = str.maketrans('', '', 'aeiou')

'example text'.translate(remove_vowels)
# 'xmpl txt'
string = 'ameer bau'
new_string = ''

for letter in string:
    if letter not in 'aeiou':
        new_string += letter

print (new_string) 
# mr b

要更改它以完全符合您的问题:

^{pr2}$

另外,str是一个保留关键字,不应将其用作变量名

相关问题 更多 >