0

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

#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 
4

1 回答 1

1

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

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

for char in secondHalf:
    if char in vowels:
        secondHalf = secondHalf.replace(char,(char.upper()))
newWord = firstHalf + secondHalf
print ("The new word is: ",newWord)
于 2013-11-04T13:11:41.893 回答