在同一个lin上打印while循环的结果

2024-09-30 22:14:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在写一个程序,它要求你输入,把你输入的句子中的单词放到一个列表中,然后让语句中的单词一个接一个地通过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.'))

我的问题: 如果我在代码末尾的原始输入中输入例如:“Hello my name is John”,我将得到以下输出:

ellohay
ymay
amenay
ishay
ohnjay

但实际上我需要以下输出:

ellohay ymay amenay ishay ohnjay

如果有人能给我解释一下如何实现这一成果,我会很感激的


Tags: 代码in字母单词listwordprint末尾
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

在打印语句末尾附加逗号(,)以避免换行:

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

相关问题 更多 >