Py学习  »  Python

为什么我的元音去除功能不起作用?(python 2.7)[副本]

sanjuro528 • 5 年前 • 1398 次点击  

我正在学习关于codecademy的python课程,并试图创建一个python函数,该函数删除字符串中的元音并返回新修改的字符串。但是,该函数返回字符串时没有任何修改(即,如果我调用anti-u元音(“abcd”),则返回“abcd”)。

在使用print语句之后,for循环似乎只运行一次,而与字符串的长度无关。

def anti_vowel(string):
    for t in string:
        if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
            string.replace(t, " ")
            print "test"
        print string
        return string
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48154
 
1398 次点击  
文章 [ 2 ]  |  最新文章 5 年前
bumblebee
Reply   •   1 楼
bumblebee    6 年前

你有 return for-a循环中的语句,这就是为什么您的代码就是您的循环只执行一次的原因。把它放在循环之外,代码就可以正常工作了。

def anti_vowel(string):
    for t in string:
        if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
            string.replace(t, " ")
        print "test"
    print string
    return string

为了替换元音字符,您不能替换现有变量,因为Python中的字符串是不可变的。你可以试试这个

def anti_vowel(string):
    for t in string:
        if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
            string=string.replace(t, " ")
        print "test"
    print string
    return string
Tim Biegeleisen
Reply   •   2 楼
Tim Biegeleisen    6 年前

python中的字符串是不可变的,因此您需要使用rhs上的替换项对原始字符串进行赋值:

if (t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
    string = string.replace(t, " ")

但是,你也可以 re.sub 在这里:

string = re.sub(r'[aeiou]+', '', string, flags=re.IGNORECASE)