找到字符串中的最后一个元音

时间:2017-09-25 13:55:31

标签: python string

我似乎无法找到正确的方法来搜索最后一个元音的字符串,并在最后一个元音之后存储任何唯一的辅音。到目前为止,我已将它设置为这样。

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

5 个答案:

答案 0 :(得分:4)

我喜欢COLDSPEED's方法,但为了完整起见,我会建议使用基于正则表达式的解决方案:

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

请参阅docs on python regular expression syntax。唯一性部分也需要进一步处理;)

答案 1 :(得分:2)

您可以撤消字符串,并使用itertools.takewhile获取所有字符,直到" last" (现在是逆转后的第一个)元音:

from itertools import takewhile

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

如果没有元音,则返回整个字符串。另外需要注意的是,您应该使用str.lower调用将输入字符串转换为小写,否则您可能无法计算大写元音。

如果您只想要独特的辅音(不重复),则需要采取进一步措施:

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

在这里,OrderedDict让我们保持秩序,同时消除重复,因为,密钥在任何字典中都必须是唯一的。

或者,如果您想要仅 出现一次的辅音,请使用:

from collections import Counter

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

答案 2 :(得分:0)

您只需为此编写一个函数:

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

例如:

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

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

它返回最后一个元音,元音的索引和最后一个元音后的所有唯一的非元音。

如果要对元音进行排序,则需要使用有序容器而不是集合,例如list(可能慢得多)或collections.OrderedDict(内存更贵但速度更快)列表)。

答案 3 :(得分:0)

您可以反转字符串并循环遍历每个字母,直到遇到第一个元音为止:

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

答案 4 :(得分:-1)

int<X>将返回单词

中的最后一个元音

last_vowel将在输入

中为您提供此元音的最后一个索引

Python 2.7

last_index

Python 3.x

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)