我試圖在字串中找到倒數第二個元音組及其索引。如果字串只包含一個元音組而不是那個元音組。
例如,在字串“impeachment”中,索引 3 處為“ea”,而在“warn”中,索引 1 處為“a”
我嘗試了 re.split() 和 find() 但不幸的是,這些方法要么洗掉我正在拆分的元音,要么只找到單獨的元音。
uj5u.com熱心網友回復:
我會這樣做:
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)
結果是:
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!
索引是一個索引范圍,端點是獨占的(如范圍函式或 python 中的切片)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527848.html
標籤:Python细绳