2016-11-26 98 views
1

對於輸入文本,我必須對所有元音進行計數,在每個單詞中首字母大寫並輸出相反的文本(不必使用大寫),而不使用標題或反向功能。我能夠計算出元音的數量,但與其他兩個人掙扎。沒有反向功能的反向字符串

def main(): 

    vowelCount = 0 
    text = 'abc' 

    while(len(text) != 0): 
     text = input('Please etner some text or press <ENTER> to exit: ') 

     for char in text: 
      if char in 'aeiouAEIOU': 
       vowelCount += 1 
     print('Vowels:', vowelCount) 
     vowelCount = 0 



     for i in text: 
      i = text.find('') + 1 
     print(i) 

     print(text[0].upper() + text[1:]) 


main() 
+0

反向或反向的每一個字符的話嗎? – AChampion

+6

[翻轉字符串已經詳細介紹了。](http://stackoverflow.com/q/931092/364696) – ShadowRanger

回答

3

以下是兩個反轉字符串的示例。 Slice the string

>>> s = 'hello' 
>>> reversed_s = s[::-1] 

或帶有循環。

res = '' 
for char in s: 
    res = char + res 

全碼

def main(): 
    # Run infinitely until break or return 
    # it's more elegant to do a while loop this way with a condition to 
    # break instead of setting an initial variable with random value. 
    while True: 
     text = input('Please enter some text or press <ENTER> to exit: ') 
     # if nothing is entered then break 
     if not text: 
      break 

     vowelCount = 0 
     res = '' 
     prev_letter = None 

     for char in text: 
      if char.lower() in 'aeiou': 
       vowelCount += 1 
      # If previous letter was a space or it is the first letter 
      # then capitalise it. 
      if prev_letter == ' ' or prev_letter is None: 
       char = char.upper() 

      res += char # add char to result string 
      prev_letter = char # update prev_letter 

     print(res) # capitalised string 
     print(res[::-1]) # reverse the string 
     print('Vowel Count is: {0}'.format(vowelCount)) 

# Example 
Please enter some text or press <ENTER> to exit: hello world! 
Hello World! 
!dlroW olleH 
Vowel Count is: 3 
+0

感謝提示的人,但是如何在沒有反轉字符串的情況下使用循環大寫每個單詞。 – MrG

+0

@MrG更新了答案。我已經分割它,所以結果字符串不是反向構建的,而是使用建議的第一種方法在結尾反轉(切片) –