Correct Code to Remove the Vowels from a String in Python

Correct code to remove the vowels from a string in Python

The function str.replace(old, new[, max]) don't changes c string itself (wrt to c you calls) just returns a new string which the occurrences of old have been replaced with new. So newstr just contains a string replaced by last vowel in c string that is the o and hence you are getting "Hey lk wrds" that is same as "Hey look words".replace('o', '').

I think you can simply write anti_vowel(c) as:

''.join([l for l in c if l not in vowels]);

What I am doing is iterating over string and if a letter is not a vowel then only include it into list(filters). After filtering I join back list as a string.

Remove vowels from a string

The comment from @arshajii explains why it is not a good idea to remove characters in the loop.
To fix the issue in YOUR code, (Note that there are more efficient ways of achieving this, but it looks like you are learning, so I shall leave it here. )

def anti_vowel(text):
vow = ["a", "e", "i", "o", "u"]
chars = []

for i in text: #No need of the two separate loops
if i.lower() not in vow:
chars.append(i)

return "".join(chars)

Demo:

>>> def anti_vowel(text):
... vow = ["a", "e", "i", "o", "u"]
... chars = []
... for i in text: #No need of the two separate loops
... if i.lower() not in vow:
... chars.append(i)
... return "".join(chars)
...
>>> anti_vowel("Hey look Words!")
'Hy lk Wrds!'
>>> anti_vowel("Frustration is real")
'Frstrtn s rl'
>>>

Removing vowels from the string python

Don't call remove on a list while iterating over it.

Think about what happens when you do it.

  • First, words = 'uURII', and i is pointing at its first character.
  • You call words.remove(i). Now words = 'URII', and i is pointing at its first character.
  • Next time through the loop, words = 'URII', and i is pointing to its second character. Oops, you've missed the U!

There are a few ways to fix this—you can iterate over a copy of the list, or you can index it from the end instead of the start, or you can use indices in a while loop and make sure not to increment until you've found something you don't want to delete, etc.

But the simplest way is to just build up a new list:

def disemvowel(word):
words = list(word)
new_letters = []
for i in words:
if i.upper() == "A" or i.upper() == "E" or i.upper() == "I" or i.upper() == "O" or i.upper() == "U":
pass
else:
new_letters.append(i)
print(''.join(new_letters))

This means you no longer need list(word) in the first place; you can just iterate over the original string.

And you can simplify this in a few other ways—use a set membership check instead of five separate == checks, turn the comparison around, and roll the loop up into a list comprehension (or a generator expression):

def disemvowel(word):
vowels = set('AEIOU')
new_letters = [letter for letter in word if letter.upper() not in vowels]
print(''.join(new_letters))

… but the basic idea is the same.

I want to delete vowels from a word in python,

string = 'ameer bau'
new_string = ''

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

print (new_string)
# mr b

To change it to exactly fit your question:

string = input('Enter your string here: ')
new_string = ''

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

print (new_string)
# mr b

Also, str is a reserved keyword, you should not use it as a variable name

Removing vowels from a list of strings

Try this :

mylist = ['sympathize.', 'sufficient.', 'delightful.', 'contrasted.','unsatiable']
vowels = ['a', 'e', 'i', 'o', 'u']
for i in range(len(mylist)):
for v in vowels:
mylist[i] = mylist[i].replace(v,"")
print(mylist)

Removing from vowels from a string

[character for character in sentence if character not in vowels] # returns list

This list comprehension should do the trick for you.

The way it works is that it takes advantage of the fact that vowels and sentences are iterables: you can define a for-loop over them, so to speak. Specifically, it pulls every character in sentence, checks if that same character does not appear in vowels, and only then does it insert it into a list.

If you want a string at the end, simply use join:

''.join([character for character in sentence if character not in vowels]) # returns string without vowels

my code to remove vowels from a string is acting weird

This weird case happens when 2 vowels are right next to each other. Basically, you are looping for each letter in the word, but when you remove the letter (if it is a vowel), then you shorten the length of the word, and therefore the next letter will have skipped over the real next letter. This is a problem when the letter being skipped is a vowel, but not when it is a consonant.

So how do we solve this? Well, instead of modifying the thing we're looping over, we will make a new string and modify it. So:

text2 = ""    
for letter in text1:
if letter not in vowels:
text2 += letter
return text2

This can also be achieved with list comprehension:

return "".join ([letter for letter in text1 if letter not in vowels])

Delete all vowels from a string using a list-comprehension

You're trying to make a list within your list-comprehension; you can just use the existing list:

return "".join([char for char in x if char not in "aeiouAEIOU"])

Note that we could even omit the list comprehension and just use a generator expression (by omitting the square brackets), but join() works internally by converting the sequence to a list anyway, so in this case using a list-comprehension is actually quicker.

removing y immediately before or after any vowel in a string in python

This is probably a homework assignment, but really the simplest (although not necessarily the fastest one) would be using regex:

import re
p = re.compile(r'(?i)y?[aeiou]y?')

p.sub('', 'may')
# 'm'

p.sub('', 'mystery')
# 'mystry'

Using pure python, you can listify your string, iterate over each character, remove characters accordingly (yes, you have done this, so you will need to modify your existing code using if statements to account for the case of "y"), and rejoin back. Here's an example.

def remove_vowels_with_y(string):
# Cache vowel set for better lookup performance.
v = set('aeiouAEIOU')
# Listify your string. This is because strings are immutable.
chars = list(string) + [''] # Sentinel character.
# Initialization.
filtered = []
prev_is_vowel = False
for i, c in enumerate(chars[:-1]):
# Add elements to `filtered` if conditions are met.
if not (c in v or (c in 'yY' and (prev_is_vowel or chars[i+1] in v))):
filtered.append(c)
prev_is_vowel = c in v

# Join filtered list and return result.
return ''.join(filtered)

remove_vowels_with_y('may')
# 'm'

remove_vowels_with_y('mystery')
# 'mystry'


Related Topics



Leave a reply



Submit