2014-09-30 46 views
0

因此,我正在編寫一個程序,要求您輸入,將您輸入的語句的單詞放入列表中,並使語句中的單詞一個接一個地通過while循環。在同一行上打印while循環的結果

while循環的工作原理如下: 如果一個單詞的第一個字母是元音,它會打印單詞+乾草。 Ifthe單詞的第一個字母是不是元音它把單詞的第一個字母在單詞的末尾+ AY

代碼:

VOWELS = ['a','e','i','o','u'] 

def pig_latin(phrase): 
    #We make sure the input is changed in only lower case letters. 
    #The words in your sentence are also putted into a list 
    lowercase_phrase = phrase.lower() 
    word_list = lowercase_phrase.split() 
    print word_list 

    x = 0 

    while x < len(word_list): 

     word = word_list[x] 
     if word[0] in VOWELS: 
      print word + 'hay' 

     else: 
      print word[1:] + word[0] + 'ay' 
     x = x+1 

pig_latin(raw_input('Enter the sentence you want to translate to Pig Latin, do not use punctation and numbers please.')) 

我的問題: 如果我例如進入:「你好,我的名字是約翰」在the_raw輸入的代碼,我會得到下面的輸出的結尾:

ellohay 
ymay 
amenay 
ishay 
ohnjay 

但其實我是想以下的輸出:

ellohay ymay amenay ishay ohnjay 

如果有人能解釋我如何實現這一目標輸出這將是appriciated

+3

'print word [1:] + word [0] +'ay',' – jonrsharpe 2014-09-30 16:36:22

回答

2

保存在另一個列表中的新詞,然後在最後:

print(" ".join(pig_latin_words)) 

例子:

VOWELS = {'a','e','i','o','u'} 

def pig_latin(phrase): 
    #We make sure the input is changed in only lower case letters. 
    #The words in your sentence are also putted into a list 
    word_list = phrase.lower().split() 
    print(word_list) 

    pig_latin_words = [] 

    for word in word_list: 
     if word[0] in VOWELS: 
      pig_latin_words.append(word + "hay") 
     else: 
      pig_latin_words.append(word[1:] + word[0] + "ay") 

    pig_latin_phrase = " ".join(pig_latin_words) 

    print(pig_latin_phrase) 

    return pig_latin_phrase 
0

在打印語句的末尾添加一個逗號(,)以避免換行符:

while x < len(word_list): 

    word = word_list[x] 
    if word[0] in VOWELS: 
     print word + 'hay', 

    else: 
     print word[1:] + word[0] + 'ay', 
    x = x+1