1

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)
Michael Kolber
  • 1,309
  • 1
  • 14
  • 23
Trevor713
  • 31
  • 2
  • Possible duplicate of [Detecting Vowels vs Consonants In Python](https://stackoverflow.com/questions/20226110/detecting-vowels-vs-consonants-in-python) – Michael Kolber Jul 18 '19 at 19:49

2 Answers2

5

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']
Mark
  • 90,562
  • 7
  • 108
  • 148
0

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']
abdusco
  • 9,700
  • 2
  • 27
  • 44