no vowels function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: no vowels function (/thread-7264.html) |
no vowels function - alex_bgtv - Jan-01-2018 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 RE: no vowels function - Mekire - Jan-01-2018 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": RE: no vowels function - squenson - Jan-01-2018 What about "y"? (See a good explanation here) RE: no vowels function - alex_bgtv - Jan-01-2018 hhh, they asked without "Y" Mekire - how about the following example https://www.tutorialspoint.com/python/string_replace.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 RE: no vowels function - squenson - Jan-01-2018 The example is correct but Mekari's point is that the initial string str is unchanged. Add after the two print statements: print str RE: no vowels function - snippsat - Jan-01-2018 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' RE: no vowels function - alex_bgtv - Jan-01-2018 Clear thanks! |