首页 > 解决方案 > 如何在作为字符串一部分的单词中查找字母并将其删除?(用 if 语句列出推导式)

问题描述

我正在尝试从字符串中删除元音。具体来说,从超过 4 个字母的单词中删除元音。

这是我的思考过程:

(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"

标签: python-3.7

解决方案


我刚刚发现“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]

我在这里找到了解决方案的一部分:在列表中查找和替换字符串值。

它被称为列表理解

我还发现了使用 If 语句的列表理解

新的代码行如下所示:

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"

推荐阅读