如何在字符串中的单词中找到字母并将其删除? (列出对if语句的理解)

时间:2019-09-22 04:04:43

标签: python-3.7

我正在尝试从字符串中删除元音。具体来说,请从四个以上字母的单词中删除元音。

这是我的思考过程:

(1)首先,将字符串拆分为一个数组。

(2)然后,遍历数组并标识超过4个字母的单词。

(3)第三,用“”替换元音。

(4)最后,将数组重新连接成字符串。

问题:我不认为代码在数组中循环。 谁能找到解决方案?

def abbreviate_sentence(sent):

    split_string = sent.split()
    for word in split_string:
        if len(word) > 4:
            abbrev = word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
            sentence = " ".join(abbrev)
            return sentence


print(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"

1 个答案:

答案 0 :(得分:0)

我刚刚发现“ abbrev = words.replace ...”这一行是不完整的。

我将其更改为:

abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") if len(words) > 4 else words for words in split_string]

我在这里找到了解决方案的一部分:Find and replace string values in list.

它称为List Comprehension

我还发现了List Comprehension with If Statement

新的代码行如下:

def abbreviate_sentence(sent):

    split_string = sent.split()
    for words in split_string:
        abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
                        if len(words) > 4 else words for words in split_string]
        sentence = " ".join(abbrev)
        return sentence


print(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"