print results of while loop on the same line
本问题已经有最佳答案,请猛点这里访问。
因此,我正在编写一个程序,要求您输入,将您输入的句子的单词放入列表中,并使语句中的单词逐个循环到while循环中。
while循环的工作方式如下:
如果单词的第一个字母是元音,则打印单词+ hay。
如果单词的第一个字母不是元音,则将单词的第一个字母放在单词的末尾+ ay
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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输入中的"Hello my name is John",我将获得以下输出:
1 2 3 4 5 | ellohay ymay amenay ishay ohnjay |
但我实际上想要以下输出:
1 | ellohay ymay amenay ishay ohnjay |
如果有人能解释我如何实现这一输出,那么它就会受到关注
将新单词保存在另一个列表中,然后在最后:
1 | print("".join(pig_latin_words)) |
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
在print语句的末尾附加一个逗号(,)以避免换行符:
1 2 3 4 5 6 7 8 9 | 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 |