Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
no vowels function
#1
Hi,
using codecademy for Python learning.
In one of the exercises, were asked to write a function deleting all vowels from a string (upper and lower).
Tried the following, didn't work. Do I misinterpret the replace function?

def anti_vowel (text):
  new = text.lower()
  for l in new:
    if l=="a" or l=="u" or l=="e" or l=="i" or l=="o":
      text.replace(l,"")
  return text
Reply
#2
replace does not work inplace (strings are immutable).
You want this:
text = text.replace(l,"")
This is, however, not an efficient way to solve this problem (computationally). You would be better to build a list and join it at the end.
Also your conditional is better written:
if l in "aeiou":
Reply
#3
What about "y"?
(See a good explanation here)
Reply
#4
hhh, they asked without "Y"
Mekire - how about the following example
https://www.tutorialspoint.com/python/st...eplace.htm

quote from the link:

The following example shows the usage of replace() method.

#!/usr/bin/python

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
When we run above program, it produces following result −

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
Reply
#5
The example is correct but Mekari's point is that the initial string str is unchanged. Add after the two print statements:
print str
Reply
#6
The point is that replace can only replace 1 word(as your example) or 1 character.
So if word is apple can't write replace('ae', '')
Have to call replace two times.
>>> text = 'apple'
>>> a = text.replace('a', '')
>>> a
'pple'
>>> b = a.replace('e', '')
>>> b
'ppl'   
But using replace is unnecessary and only make the task more difficult than it is.
Here a hint.
>>> text = 'apple'
>>> letters = []
>>> for char in text:     
...     if char not in 'aeiou':
...         letters.append(char)
... 
>>> letters
['p', 'p', 'l']
>>> ''.join(letters)
'ppl' 
Reply
#7
Clear
thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  remove vowels in word with conditional ambrozote 12 4,006 May-02-2021, 06:57 PM
Last Post: perfringo
  counting vowels in a string project_science 3 2,510 Dec-30-2020, 06:44 PM
Last Post: buran
  Counting vowels in a string (PyBite #106) Drone4four 4 2,206 Jul-07-2020, 05:29 AM
Last Post: theknowshares
  replace vowels niru 9 20,615 Sep-26-2017, 12:46 PM
Last Post: nilamo
  Vowels and Consonants detector OmarSinno 5 9,709 Sep-21-2017, 02:27 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020