Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing characters from string Python

Tags:

python

string

I'm trying to write a function that gets rid of the vowels in a given string, but it seems to not behave the way it should do...

def anti_vowel(text):
    for c in text:
        if c in "aeiouAEIOU":
            no_vowel = text.replace(c, '')
    return no_vowel
print(anti_vowel('Hello World')

so instead of printing

Hll Wrld

It prints

Hell Wrld  

Thanks (in advance) for helping

like image 340
Remo Totoro Avatar asked Dec 02 '22 13:12

Remo Totoro


2 Answers

The problem is that no_vowel only has the value of the last time that text.replace(c, '') was executed. Another issue is that no_vowel only gets a value when there is actually a vowel to remove; the code would fail on anti_vowel('vwllss'). Furthermore, you don't have to check whether a character is contained in the text before calling str.replace().

This should work:

def anti_vowel(text):
    for vowel in "aeiouAEIOU":
        text = text.replace(vowel, '')
    return text
print(anti_vowel('Hello World'))

As others indicated, another approach would be to write code in a different way:

def anti_vowel(text):
    ''.join(c for c in text if c not in 'aeiouAEIOU')

Please do use a generator expression in ''.join() and not a list comprehension; such a list comprehension would allocate memory unnecessarily.

like image 122
dr. Sybren Avatar answered Dec 17 '22 04:12

dr. Sybren


You can use string.translate() for this. For example:

def anti_vowel(text):
  return text.translate(None, "aeiouAEIOU")

print(anti_vowel("hello world"))

With Python 3 the delete argument is gone, but you can still do it by mapping a character to None.

def anti_vowel_py3(text):
   return text.translate({ord(i): None for i in "aeiouAEIOU"})

print(anti_vowel_py3("hello world"))
like image 38
kichik Avatar answered Dec 17 '22 04:12

kichik