Find the last vowel in a string

I cant seem to find the proper way to search a string for the last vowel, and store any unique consonants after that last vowel. I have it set up like this so far.

word = input('Input a word: ')
wordlow = word.lower()
VOWELS = 'aeiou'
last_vowel_index = 0

for i, ch in enumerate(wordlow):
    if ch == VOWELS:
        last_vowel_index += i

print(wordlow[last_vowel_index + 1:])

You can reverse your string, and use itertools.takewhile to take everything until the "last" (now the first after reversal) vowel:

from itertools import takewhile

out = ''.join(takewhile(lambda x: x not in set('aeiou'), string[::-1]))[::-1]
print(out)
'ng'

If there are no vowels, the entire string is returned. Another thing to note is that, you should convert your input string to lower case using a str.lower call, otherwise you risk not counting uppercase vowels.


If you want unique consonants only (without any repetition), a further step is needed:

from collections import OrderedDict
out = ''.join(OrderedDict.fromkeys(out).keys())

Here, the OrderedDict lets us keep order while eliminating duplicates, since, the keys must be unique in any dictionary.

Alternatively, if you want consonants that only appear once, use:

from collections import Counter

c = Counter(out)
out = ''.join(x for x in out if c[x] == 1)

You can reverse your string, and use itertools.takewhile to take everything until the "last" (now the first after reversal) vowel: from itertools import takewhile out = ''.join(takewhile(lambda x: x not in set('aeiou'), string[::-1])) [::-1] print(out) 'ng'. If there are no vowels, the entire string is returned.

I like COLDSPEED's approach, but for completeness, I will suggest a regex based solution:

import re
s = 'sjdhgdfgukgdk'
re.search(r'([^AEIOUaeiou]*)$', s).group(1)
# 'kgdk'

# '[^AEIOUaeiou]'  matches a non-vowel (^ being the negation)
# 'X*'  matches 0 or more X
# '$' matches the end of the string
# () marks a group, group(1) returns the first such group

See the docs on python regular expression syntax. Further processing is also needed for the uniqueness part ;)

Java 8 Object Oriented Programming Programming You can read a character in a String using the charAt () method. To find the vowels in a given String you need to compare every character in it with the vowel letters.

You can simply write a function for that:

def func(astr):
    vowels = set('aeiouAEIOU')

    # Container for all unique not-vowels after the last vowel
    unique_notvowels = set()

    # iterate over reversed string that way you don't need to reset the index
    # every time a vowel is encountered.
    for idx, item in enumerate(astr[::-1], 1):  
        if item in vowels:
            # return the vowel, the index of the vowel and the container
            return astr[-idx], len(astr)-idx, unique_notvowels
        unique_notvowels.add(item)

    # In case no vowel is found this will raise an Exception. You might want/need
    # a different behavior...
    raise ValueError('no vowels found')

For example:

>>> func('asjhdskfdsbfkdes')
('e', 14, {'s'})

>>> func('asjhdskfdsbfkds')
('a', 0, {'b', 'd', 'f', 'h', 'j', 'k', 's'})

It returns the last vowel, the index of the vowel and all unique not-vowels after the last vowel.

In case the vowels should be ordered you need to use an ordered container instead of the set, for example a list (could be much slower) or collections.OrderedDict (more memory expensive but faster than the list).

Approach: Traverse the string character by character and check if the current character is a vowel. If current character is a vowel then concatenate it to the resultant string, result. If at any point the length of the resultant string becomes X then print the string result else print -1 in the end.

You can just reverse your string and loop over each letter until you encounter the first vowel:

for i, letter in enumerate(reversed(word)):
    if letter in VOWELS:
        break
print(word[-i:])

In this method, we form a dictionary with the vowels and increment them when a vowel is encountered. In this method, we use the case fold method to ignore the cases, following which we form a dictionary of vowels with the key as a vowel. This is a better and efficient way to check and find the number of each vowel present in a string.

last_vowel will return the last vowel in the word

last_index will give you the last index of this vowel in the input

Python 2.7

input = raw_input('Input a word: ').lower()
last_vowel = [a for a in input if a in "aeiou"][-1]
last_index = input.rfind(last_vowel)
print(last_vowel)
print(last_index)

Python 3.x

input = input('Input a word: ').lower()
last_vowel = [a for a in input if a in "aeiou"][-1]
last_index = input.rfind(last_vowel)
print(last_vowel)
print(last_index)

Program to remove vowels from a String; Remove consecutive vowels from string; Program to count vowels in a string (Iterative and Recursive) Number of distinct permutation a String can have; Check if both halves of the string have same set of characters; Count words that appear exactly two times in an array of words

Find Vowels In A String ā€“ Using Switch Case 1) Read the entered string using scanner class object sc.nextLine (), and store in the variable ā€œsā€ which is string type. 2) The for loop iterates from j=0 to j< length of the string. The variable ch assigned with the charter which is at the jth position in the string.

C Program to Count Vowels and Consonants in a String Example 1. This program allows the user to enter a string (or character array). Next, it will count how many numbers of Vowel and Consonant present in the user-specified string using If Else Statement.

C program to find the first vowel in a string : In this C programming tutorial, we will learn how to find first vowel in a string using C language. For example, for the string Hello World !!, the first vowel is e.This character should be print out by the program. The user will enter one string, our program will read it and store it in an array.

Comments
  • Why are you adding i onto last_vowel_index ?
  • Are you talking about in the if loop, or when printing? Or hell, even both?
  • last_vowel_index += i <-- this. I can't think of any reason for this.
  • @schwobaseggl Hmm, didn't see that. Think it should be fine now.
  • OP is unclear by what is meant by 'unique consonants'. Does me mean consonants that occur only 1 time after the last vowel or does he simply want to remove duplicates?
  • @DavidJenkins Edited. These nitpicks are easy to address.
  • @david Jenkins, for example if hell was input, it would just store one l
  • @manoman181 I think the 2nd section of my answer addresses your problem quite nicely.
  • Nice one. You should add a brief explanation on the regex and how it works.