简体   繁体   中英

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:])

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 ;)

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 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).

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:])

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM