我尝试定义一个从字符串中删除元音的函数。第4行检测到错误,内容如下: “TypeError:'unicode'对象不支持项目分配”。 有人可以用简单的语言解释这个错误是什么以及如何解决它?
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)
答案 0 :(得分:0)
字符串是不可变对象,您无法在原地更改它们。相反,您可以使用str.replace
删除字符:
text.replace(character, "")
同样在你的代码中你不需要使用range
,因为字符串是可迭代的,你可以循环遍历字符串并检查元音列表中每个字符的存在。
def del_vowel(text):
for i in text:
if i.lower() in ['a','e','i','o','u']:
text.replace(i,"")
return text
但是你可以使用str.translate
从字符串中删除某些字符,这是一种更加pythonic的方法。
阅读以下问题以获取更多信息:Remove specific characters from a string in python
答案 1 :(得分:0)
使用Generator Expressions的单行代码:
"".join([char if char not in ['a','e','i','o','u'] else "" for char in text])