Home > other >  How can I find the penultimate occurrence of a group of vowels in a string in python?
How can I find the penultimate occurrence of a group of vowels in a string in python?

Time:11-04

I'm trying to find the penultimate vowel group and its index in a string. If the string only contains one vowel group than its that one.

For example in the string "impeachment" it would be "ea" at the index 3 And in "warn" it would be "a" at the index 1

I tried re.split() and find() but unfortunately these approaches either delete the vowel which I am splitting or only find separate vowels.

CodePudding user response:

I would do it like this:

import re


def find_penultimate_or_last_vowel_group(string):
    print(f"Word: {string}")
    
    matches = list(re.finditer("[AEIOUaeiou] ", string))
    if not matches:
        print("No vowel-group found!")
        return
    match = matches[-2] if len(matches) > 1 else matches[-1]

    print(f"Vowel-group: {string[match.start():match.end()]}")
    print(f"Index: {match.span()}\n")


words = ["impeachment", "warn", "IchmitZ", "Rhythm"]
for word in words:
    find_penultimate_or_last_vowel_group(word)

The result is:

Word: impeachment
Vowel-group: ea
Index: (3, 5)

Word: warn
Vowel-group: a
Index: (1, 2)

Word: IchmitZ
Vowel-group: I
Index: (0, 1)

Word: Rhythm
No vowel-group found!

The Index is an index-range with the end-point being exclusive (like for the range-function or slicing in python).

  • Related