如何匹配元音?

3 投票
6 回答
7116 浏览
提问于 2025-04-16 12:02

我在做一个大程序的时候,遇到了一个小问题。简单来说,我需要让用户输入一个单词,然后我想打印出第一个元音字母的位置。

word= raw_input("Enter word: ")
vowel= "aeiouAEIOU"

for index in word:
    if index == vowel:
        print index

但是,这个方法没有成功。到底哪里出了问题呢?

6 个回答

2

这里有一个用列表推导式实现的相同想法:

word = raw_input("Enter word: ")
res = [i for i,ch in enumerate(word) if ch.lower() in "aeiou"]
print(res[0] if res else None)
4

为了与众不同:

import re

def findVowel(s):
    match = re.match('([^aeiou]*)', s, flags=re.I)
    if match:
        index = len(match.group(1))
        if index < len(s):
            return index
    return -1  # not found
5

试试这个:

word = raw_input("Enter word: ")
vowels = "aeiouAEIOU"

for index,c in enumerate(word):
    if c in vowels:
        print index
        break

for .. in 这个写法会逐个遍历字符串里的实际字符,而不是它们的位置索引。使用 enumerate 可以同时得到字符的位置和字符本身,这样引用这两者会更方便。

撰写回答