Trevor713
Trevor713

Reputation: 31

From a string, how do you return only the words that don't begin with a vowel?

I have a string E.g. "A dog is a good pet"

I would like to be able to return only the words that begin with a consonant. ["dog", "good", "pet"] as a list

def consonant_first(newstr):
    for char in newstr.split():
        if char[0] in newstr.split() ==  vowels1:
            return newstr.split() 
print(newstr)

Upvotes: 1

Views: 78

Answers (2)

Mark
Mark

Reputation: 92450

Just test the first letter in a list comprehension:

s = "A dog is a good pet"

def consonant_first(newstr):
    return [word for word in s.split() if  word[0].lower() not in 'aeiou']

print(consonant_first(s))

Make sure to test against all cases so you catch the A.

result:

['dog', 'good', 'pet']

Upvotes: 5

abdusco
abdusco

Reputation: 11101

Here's a solution that uses iterators in case you're planning on processing very large amount of text:

import re

def find_consonant_words(text: str):
    vowels = set("aeiou")

    for m in re.finditer('\S+', text):
        w = m.group(0)
        if w[0].lower() not in vowels:
            yield w

string = "A very long text: a dog is a good pet"

for w in find_consonant_words(string):
    print(w)

# get it all as a list
consonant_words = list(find_consonant_words(string))
print(consonant_words)

output:

very
long
text:
dog
good
pet
['very', 'long', 'text:', 'dog', 'good', 'pet']

Upvotes: 0

Related Questions