1

I tried to define a function that removes vowels from a string. An error was detected at line 4 that reads: "TypeError: 'unicode' object does not support item assignment". Could somebody please explain in simple terms what this error is about and how to fix it?

def del_vowel(text):
    for i in range(len(text)):
        if text[i].lower() in ['a','e','i','o','u']:
            text[i] = ""
    return text
text = raw_input('> ')
print del_vowel(text)
skyman
  • 15
  • 5
  • string are immutable in python – styvane Oct 10 '15 at 16:27
  • Does this answer your question? [Remove specific characters from a string in Python](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) – Georgy Jul 05 '20 at 12:11
  • Duplicate explaining the error: ['str' object does not support item assignment in Python](https://stackoverflow.com/q/10631473/7851470) – Georgy Jul 05 '20 at 12:12

2 Answers2

0

Strings are immutable objects you can not change them in-place.Instead you can use str.replace to remove the characters :

text.replace(character, "")

Also in your code you don't need to use range, since strings are iterable you can loop over the string and check the existence of each character in list of vowels.

def del_vowel(text):
    for i in text:
        if i.lower() in ['a','e','i','o','u']:
            text.replace(i,"")
    return text

But a more pythonic way you can use str.translate to remove some character from your string.

Read the following question for more info :Remove specific characters from a string in python

Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

A one-liner using Generator Expressions:

"".join([char if char not in ['a','e','i','o','u'] else "" for char in text])
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86