This question already has answers here:
Loop "Forgets" to Remove Some Items [duplicate]
(10 answers)
Closed 8 years ago.
I'm going through some exercises in CodeAcademy. In one they ask you to write a function to remove all the vowels from a string.
Apparently my function works with different texts, but it's not working with: "Hey look Words!". That's weird. Which could be my error?
My code:
def anti_vowel(text):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
letters = []
for char in text:
letters.append(char)
for i in vowels:
for j in letters:
if i==j:
letters.remove(j)
new_text = ''.join(letters)
print new_text
Your problem is that you are modifying letters while iterating over it. Instead, try building a new list (and a few other changes):
no_vowels = []
for j in letters:
if j not in vowels:
no_vowels.append(j)
new_text = ''.join(no_vowels)
You can always do like this. You have to use another variable for new string.
>>> vowels = ['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']
>>> string = "Hey look Words!"
>>> new_string = ""
>>> for s in string:
if s not in vowels:
new_string += s
>>> print new_string
Hy lk Wrds!
Related
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:
letters = ['R', 'E', 'T', 'O', 'P', 'A']
letters = ['R', 'E', 'T', 'O', 'P', 'A']
final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]
Does anybody have an idea of how to do that?
Thank you in advance!
You can use this way to solve the problem.
letters = ['R', 'E', 'T', 'O', 'P', 'A']
words_list = ["TOP", "CUT", "REPORT", "GOOD"]
final_list = [word for word in words_list if set(word).issubset(set(letters))]
print(final_list)
In this code, we are checking each word in the words_list whether that word is made of letters in the letters_list. To do that we use the issubset method.
set(word).issubset(set(letters)) this part of code is return a boolean value. We include that word to final_list if and only if that boolean value is True.
You are almost there, you just need to tweak your all condition a bit.
all(word for letter in letters if letter in word) -> this would return True as long as any word is True which would always be the case.
What we want to check is that "all letters in the word are part of letters", letter in letters in the following code would return True/False if a letter is in letters. So with all, it would only return True if all letter in letters checks return True.
letters = ['R', 'E', 'T', 'O', 'P', 'A']
dictionary = ['REPORT', 'INVALID', 'ROPE']
final_list = [word for word in dictionary if all(letter in letters for letter in word)]
print(final_list)
outputs -
['REPORT', 'ROPE']
You can use the filter() method in python
letters = ['R', 'E', 'T', 'O', 'P', 'A']
my_lis = ['jake','jill','tim','vim']
def foo(x):
for words in x:
for letter in words:
print(letter)
if letter in letters:
return True
else:
return False
final = filter(foo,my_lis)
for x in final:
print(x)
You can filter your list using python filter() method.
This question already has answers here:
Correct code to remove the vowels from a string in Python
(13 answers)
Closed 4 years ago.
I'm beginning to learn Python and I'm trying to create a function that removes vowels from a given string.
This is my Code :
def anti_vowel(text):
li = []
for l in text:
li.append(l)
while 'a' in li:
li.remove('a')
while 'A' in li:
li.remove('A')
while 'A' in li:
li.remove('e')
while 'e' in li:
li.remove('E')
while 'E' in li:
li.remove('i')
while 'i' in li:
li.remove('I')
while 'I' in li:
li.remove('o')
while 'o' in li:
li.remove('O')
while 'u' in li:
li.remove('u')
while 'U' in li:
li.remove('U')
return "".join(li)
I get the "list.remove(x): x not in list" error when I try to run it.
I know this error's been already asked about here but I didn't really get the answers in those specific cases.
thanks for reading and please help :)
def anti_vowel(text):
li = ''
for l in text:
if l.lower() not in 'aeiou':
li+=l
return li
You are overcomplicating it, just use a generator expresion:
def anti_vowel(text):
return "".join(x for x in text if x not in "AEIOUaeiou")
>>> anti_vowel("asldkfoihyoihbiw")
'sldkfhyhbw'
You can use loops also:
def anti_vowel(text):
li = []
for l in text:
if l not in "AEIOUaeiou":
li.append(li)
return "".join(li)
You have some mis-matches in your while statement, for example:
while 'e' in li:
li.remove('E')
If there is no 'E' but there is an 'e' this will cause a problem.
You either need to go through and make sure they are consistent.
Or you could write a small function to deal with each vowel:
def remove(letters, vowel):
while vowel in letters:
letters.remove(vowel)
You can then call this for each vowel.
def anti_vowel(text):
li = []
for l in text:
li.append(l)
for vowel in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
remove(li, vowel)
return "".join(li)
A more Pythonic way would be to pull out the required letters, using a list comprehension or generator, as per the answer from Netware. I'm just pointing out the source of your error.
If you catch yourself repeating something lots, and copy/pasting then tweaking, you can easily miss a few places that need tweaking.
Try to change the repeats into a function.
This question already has answers here:
Correct code to remove the vowels from a string in Python
(13 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 5 years ago.
def disemvowel(string):
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
listString = list(string)
for t in listString:
if t in vowels:
listString.remove(t)
string = ''.join(listString)
return string
The function is supposed to remove all the vowels and if the input is:
'This website is for losers LOL!'
The correct output should be:
'Ths wbst s fr lsrs LL!'
But the moment I changed the input to have vowels appear consecutively with each other i.e.
'This websitea is for loosers LOL!'
The output becomes
'Ths wbsta s fr losrs LL!'
which is incorrect (see 'wbsta' and 'losrs').
Instead of removing the vowels, why not just construct the string from the characters that aren't vowels?
return ''.join([c for c in string if c not in vowels])
It's generally not a good idea to remove items from the thing you're iterating from, because this can cause implications during the iteration. Therefore, instead of removing the characters that are vowels from the string, instead add the characters that aren't vowels to a new string.
def disemvowel(string):
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
listString = list(string)
string = ""
for t in listString
if t not in listString
string += t
return string
let's say
there's a list
vowels = ['a', 'e', 'i', 'o', 'u']
x = raw_input("Enter something?")
Now how to find instances of these vowels in the x? I want to modify x so that it contains only non vowel letters.
.find won't work.
vowels = {'a', 'e', 'i', 'o', 'u'}
x =input('Enter...')
new_string = ''.join(c for c in x if c not in vowels)
Will create a new copy of x minus the vowels saved as new_string. I have changed vowels to be a set so that look up time is faster (somewhat trivial in this example but it's a good habit to sue where appropriate). Strings are immutable so you can't just take the letters out of x, you have to create a new string that is a copy of x without the values you don't need. .join() puts the whole thing back together.
You can use the count function for each letter. For example x.count('a') would count how many 'a' are in the word. The iterate over all the vowels and use sum to find the total number of vowels.
vowelCount = sum(x.count(vowel) for vowel in vowels)
from collections import Counter
vowels = {'a', 'e', 'i', 'o', 'u'}
s = "foobar"
print(sum(v for k,v in Counter(s).items() if k in vowels))
3
Or use dict.get with a default value of 0:
s = "foobar"
c = Counter(s)
print(sum(c.get(k,0) for k in vowels))
3
You can use like this,
>>> st = 'test test'
>>> len(re.findall('[aeiou]', st, re.IGNORECASE))
2
Or,
>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> sum(map(lambda x: vowels.count(x) if x in vowels else 0, st))
2
Or,
>>> len([ ch for ch in st if ch in vowels])
2
So I just learned how to manipulate single letters in a for loop from code academy.
But let's say I made a function and wanted this function to manipulate the vowels of an user inputted word and replace the vowel with four consecutive copies of itself. How would I go about that?
Expected output:
>>>Exclamation("car")
caaaar
>>>Exclamation("hello")
heeeelloooo
So far I have:
word = input("Enter a word: ")
vowels= ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in word:
if char in vowels:
print(____,end='') #here I am unsure of how to replace it with consecutive copies of itself
else:
print(char,end='')
Your print statement can be:
print(4 * char,end='') # Or how many ever times you want to repeat it.
If word is 'car', this code:
>>> for char in word:
... if char in vowels:
... print(4 * char, end='')
... else:
... print(char, end='')
...
prints
caaaar
Note: You can include only the lower case vowels in your vowels list and in your if condition, check if char.lower() is in vowels.