1

I'm trying to make a program that deleted all vowels from a string but for some reason it is not working. Here is my code in python 3

s = list(input())

vowels = ["A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y"]

for i in s:
    if i in vowels:
        s.remove(i)

The code works except for when two vowels are adjacent to each other since it skips and iteration. Please let me know if any of you have any ideas on how I could solve this small issue, thanks!

  • 1
    `s = s.remove(i)`? Also, don't delete while iterating. Better use a list comprehension or regular expression. – tobias_k Jun 25 '20 at 14:27
  • Also see [Remove specific characters from a string in Python](https://stackoverflow.com/q/3939361/7851470) – Georgy Jun 28 '20 at 11:58

5 Answers5

5

Using list comprehension and join

s = 'Hello world!'
vowels = 'AEIOUYaeiouy'
print(''.join([l for l in s if l not in vowels]))

>>> Hll wrld!
ScootCork
  • 3,411
  • 12
  • 22
5

The often-overlooked str.translate is blazingly fast for this. To only delete characters, you can build a translation table using just the third argument of maketrans() If you are dealing with more than tiny text, it may be a better option over a regex:

removeVowels = str.maketrans("","",'AEIOUYaeiouy')
s = "Hello There"
s.translate(removeVowels)
#'Hll Thr'
Mark
  • 90,562
  • 7
  • 108
  • 148
1

Using re

import re

s = input()
vowels = ["A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y"]

print(re.sub('|'.join(vowels), '', s)
Jab
  • 26,853
  • 21
  • 75
  • 114
1

Here's what you can do:

s = input()

vowels = ["A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y"]

s = ''.join([i for i in s if i not in vowels])
Red
  • 26,798
  • 7
  • 36
  • 58
1

This uses Regex to solve your problem.

import re

s = input()
results = re.sub(r'[AEIOUYaeiouy]', '', s)

The syntax of re.sub() is:

re.sub(regex_pattern, replacement, input_string)
The method returns a string where matched occurrences are replaced with the content of replacement variable.

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33