所以我正在编写一个程序,询问你的输入,把你输入的句子的单词放入一个列表中,并使语句中的单词逐个进入while循环。
while循环的工作方式如下: 如果单词的第一个字母是元音,则打印单词+ hay。 如果单词的第一个字母不是元音,则将单词的第一个字母放在单词的末尾+ 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输入中的“Hello my name is John”,我将得到以下输出:
ellohay
ymay
amenay
ishay
ohnjay
但我实际上想要以下输出:
ellohay ymay amenay ishay ohnjay
如果有人可以解释我如何实现这个输出,那么它将是适当的
答案 0 :(得分: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
答案 1 :(得分:0)
在print语句的末尾附加一个逗号(,)以避免换行符:
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