Skip to content Skip to sidebar Skip to footer

Selecting The First Consonant In A Word (following A Number Of Vowels)

Hi I am trying to make a pig-latin translator and a problem arose when I tried to deal with words beginning in vowels. The aim would be that, for words with vowels at the beginning

Solution 1:

Try this:

VOWELS = ('a', 'e', 'i', 'o', 'u')

deffirst_consonant(word):
    for letter in word:
        if letter.lower() notin VOWELS:
            return letter

defpig_latin(word):
    return'%s-%say' % (word, first_consonant(word) or word[0])

It tries to find the first consonant in a word and appends ay to the end. If it's not present then it defers to the first letter of the word (I don't know if this is correct, but you can adapt it to your needs).

Solution 2:

We can get the next constonant and its index using a generator expression. If there is no constotnant, we will return (None, None) instead

next(((letter, index) for index, letter inenumerate(word) if letter notin'aioue'), (None, None))

We can break this down a little bit to understand what's going on.

enumerate is a function that returns an iterator that pairs elements in an iterable with their index. So list(enumerate('abc')) is [(0, 'a'), (1, 'b'), (2, 'c')]. We want to get the index of the first consonant so we know where to slice.

((letter, index) for index, letter in enumerate(word) if letter not in 'aioue') is a generator expression. A generator is will yield values one by one. All this one does is filter out the vowels from our enumerated letters.

next(generator, (None, None)) gets us the next item out of the generator (which will be the first item). If there is no next item (a word of all vowels), it will return the second argument (None, None)

Post a Comment for "Selecting The First Consonant In A Word (following A Number Of Vowels)"