如何在字符串大写的后半部分中创建所有元音?

时间:2013-11-04 13:04:14

标签: string python-3.x uppercase

我正在尝试在字符串大写的后半部分中创建所有元音。这就是我到目前为止所做的,我似乎无法得到我想要的结果。

#Ask user for word
word = str(input("Please enter a word: "))

#Count word length
wordLen = len(word)

#Count half of word length
halfWordLen = int (wordLen/2)

#Obtain 1st and 2nd half of the word
firstHalf = word[:halfWordLen]
secondHalf = word[halfWordLen:]

#Determine vowels
vowels = set(['a','e','i','o','u'])

#Iterate through 2nd half to find vowel.
#Then, uppercase the vowels, and display new word.
for char in secondHalf:
    if char in vowels:
        newWord = firstHalf + secondHalf.replace(char,(char.upper()))
        print ("The new word is: ",newWord)

结果:

Please enter a word: abrasion
The new word is:  abrasIon
The new word is:  abrasiOn

应该是:

Please enter a word: abrasion
The new word is:  abrasIOn 

1 个答案:

答案 0 :(得分:1)

您的代码存在两个问题。首先,当你在下半场更换元音时,你只是暂时这样做。您需要在单独的行中执行该操作,并将其保存在后半部分变量中。

此外,每次循环播放时都会打印临时结果。如果您只希望它只打印一次,只需降低缩进级别,使其位于循环外部。这是我如何重组它。

for char in secondHalf:
    if char in vowels:
        secondHalf = secondHalf.replace(char,(char.upper()))
newWord = firstHalf + secondHalf
print ("The new word is: ",newWord)