如何从数组中的字符串中删除字母?

时间:2016-12-04 19:16:53

标签: python arrays string

我有这个数组ar,我需要删除其中每个单词的元音。我该怎么做?我已经尝试过.pop和.remove了但是没有用。

ar=["house","place","oipa"]

def noWovels(inList):
    wovels=["a","e","i","o","u","y"]
    for word in inList:
        for letter in word:
            if letter in wovels:
                inList[word].remove(letter) ?
                inList.replace(letter,"") ?
                word.pop(letter) ?
    return inList

print(noWovels(ar))

3 个答案:

答案 0 :(得分:1)

使用简单的 list comprehension 表达式可以实现相同的目的:

>>> vowels = 'aieou'
>>> word_list = ["house","place","oipa"]
>>> [''.join(c for c in word if c not in vowels) for word in word_list]
['hs', 'plc', 'p']

或者,在列表理解(未建议)中使用filter作为:

>>> [''.join(filter(lambda c: c not in vowels, word)) for word in word_list]
['hs', 'plc', 'p']

<强>解释

这些列表理解表达式逻辑等同于:

new_list = []
for word in word_list:
    new_word = ''
    for c in word:
        if c not in vowels:
            new_word += c
    new_list.append(new_word)

答案 1 :(得分:0)

列表理解应该是整洁的。

>>> [''.join(j for j in i if j not in 'aeiou') for i in ar]
['hs', 'plc', 'p']

答案 2 :(得分:0)

根据您的代码:

ar = ["house", "place", "oipa"]

def noWovels(inList):
    wovels = ["a", "e", "i", "o", "u", "y"]
    for i, word in enumerate(inList):
        for w in wovels:
            word = word.replace(w, "")
        inList[i] = word

    return inList

print(noWovels(ar))