如何找到元音在字符串输入中的位置,并在输出中打印它们?

问题描述 投票:0回答:2

我必须编写一个脚本,在该脚本中提示用户输入字符串,代码获取字符串并查找每个值的位置。例如,如果我输入“ apple”,输出将为0和4。该脚本必须具有两个功能,其中第一个要求用户输入,第二个要求元音。

我问过我的老师,他带领我了解了我现在所拥有的,但是我无法从那里得到它。

def askForString():
    theString=str(input("Please enter a string: "))
    theString=theString.lower()
    return theString

def findVowels(TheString,vowels):
    for i in range(len(TheString)):
        if TheString[i] in vowels:
            TheString=TheString[i]
            return [i]

def main():
    TheString=askForString()
    vowels="aeiou"
    TheVowels=findVowels(TheString,vowels)
    print(TheVowels)

main()
python-3.x
2个回答
0
投票
string = input("Enter a line of text: ")
vowels = set("aeiou")
for index, char in enumerate(string):
    if char in vowels:
        print(index)

如果输入'apple',它将返回'0'和'4'。

如果输入'ukulele',它将返回'0','2','4','6'。

只需将以上内容拆分为两个功能。


0
投票

如果您已经走了那么远,可以用字典方便地实现:

def vowelFinder(mystring):
    vowels = ('a','e','i','o','u')              #tuples are preferable for efficiency
    results = {}                                #dict for {vowel:[position list]} pairs
    for x in vowels:
        for y in range(len(mystring)):
            if x in results.keys() and x == mystring[y].lower():
                results[x].append(y)                              #alter a dict entry
            elif x = mystring[y].lower():
                results.update({x:[y]}                            #make a dict entry
    return results

请注意使用str.lower()以避免丢失大写的元音。然后,如果我们尝试类似的东西:

vowelFinder('I have asked my teacher, and he led me to what I have now, but I cannot get it from there.')
{'a': [3, 7, 18, 25, 44, 50, 66],
 'e': [5, 10, 17, 21, 30, 33, 37, 52, 73, 86, 88],
 'i': [0, 47, 63, 76],
 'o': [40, 55, 69, 81],
 'u': [60]}
© www.soinside.com 2019 - 2024. All rights reserved.