如何将元音替换为另一个值?(a到e,e到i等)

时间:2019-11-07 16:44:13

标签: python-3.x

我需要能够让用户输入一个字符串,并且我的代码应该能够查看该字符串并更改元音。所以所有的a变成e,所有的e变成我,依此类推。这就是我所拥有的,但是我不知道如何使其正常工作。

def askForString():
    userString=str(input("Enter a string: "))
    userString=userString.lower()
    return userString

def changeVowels(theString,vowels):
    newString=[]
    #newVowels=['e','i','o','u','a']
    for i in range(len(theString)):
        if theString[i] in vowels:
            i+=newString
        newString.append(i)
    return newString

def main():
    theString=askForString()
    vowels=["a","e","i","o","u"]
    NewString=changeVowels(theString,vowels)
    print(NewString)

main()

我认为我需要以某种方式将元音更改为新的元音,但我不知道该如何做。这就是为什么我要对此发表评论。

2 个答案:

答案 0 :(得分:0)

def changeVowels(theString, vowels):
    newString=[]
    repls = dict(zip(vowels, vowels[1:]+[vowels[0]]))
    for theLetter in theString:
        if theLetter in vowels:
            theLetter = repls[theLetter]
        newString.append(theLetter)
    return newString

答案 1 :(得分:0)

i+=newString行是错误的。 i是一个整数,而newString是一个列表。您不能在列表中添加整数。

从我的问题中得知,您需要按以下方式替换字符串中的元音:

a -> e
e -> i
i -> o
o -> u
u -> a

您可以通过多种方式实现这一目标:

方法1:

inputString = input() # input returns string by default, no need to call with with str()

outputString = ""
vowels = ['a','e','i','o','u']

for character in inputString:
    if character in vowels:
        vowelIndex = vowels.index(character) # get the index of the vowel
        if vowelIndex == len(vowels)-1: # if its 'u', then we need to cycle back to 'a'
            vowelIndex = 0
        else:
            vowelIndex += 1 # if its not 'u', then just add 1 to go to next index which gives us the next vowel
        outputString += vowels[vowelIndex] # put that character into the outputString
    else:
        outputString += character  # if not vowel, then just put that character into the string.

print(outputString)

方法2:使用字典将元音直接映射到下一个元音

vowels = {
    "a" : "e",
    "e" : "i",
    "i" : "o",
    "o" : "u",
    "u" : "a"
}

inputString = input()
outputString = ""

for character in inputString:
    if character in vowels: # checks the a key named "character" exists in the dictionary "vowels
        outputString += vowels[character]
    else:
        outputString += character

print(outputString)