-1

How to delete the vowel from the given string?

letter = 'raeiou'
new_string = []
for i in letter:
    new_string.append(i)
for j in new_string:
    if j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u':
        new_string.remove(j)
        final = ''.join(new_string)
print('The string after removing the vowels is {}'.format(final))

expected output r but reo

  • 1
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Mihai Chelaru Oct 28 '19 at 13:22

3 Answers3

0

Here is an alternative suggestion:

def func(s):
    for c in 'aeiouAEIOU':
        s = ''.join(s.split(c))
    return s
goodvibration
  • 5,980
  • 4
  • 28
  • 61
0

When you do:

for j in new_string:
    ...
    new_string.remove(...)

you are modifying a list while looping on it (see e.g. strange result when removing item from a list).

You could simply skip vowels when you create new_list in the first place:

for i in letter:
  if not i in 'aeiou':
    new_string.append(i)
final = ''.join(new_string)
Demi-Lune
  • 1,868
  • 2
  • 15
  • 26
0

You don't need two loops for this!

letter = 'raeiou'
new_string = letter
vowels = ('a', 'e', 'i', 'o', 'u')
for i in letter:
    if i in vowels:
        new_string = new_string.replace(i,"");
print('The string after removing the vowels is {}'.format(new_string))
garlicFrancium
  • 2,013
  • 14
  • 23