猪拉丁语在Python转换

时间:2018-04-14 23:47:18

标签: python

def convert_pig_latin(pig):
    first_letter = pig[0]
    #Check if Vowel
    if first_letter in 'aeiou':
        pig_word = pig + 'ay'
    else:
        pig_word = pig[1:] + first_letter + 'ay'   
        print('Pig Latin:',pig_word)

所以基本上,这仅适用于1个单字输入。假设用户输入一个句子,它将无法正常工作。这段代码在我的函数选项卡中,我的主模块当然用给定的输入句子运行它。有人可以帮我解决一下如何用一整句而不是一个单词--.-尝试使用for循环但是搞砸了。

欣赏它,谢谢!

2 个答案:

答案 0 :(得分:2)

你可以在这里使用列表理解:

def pig_latin(sentence):
  return ' '.join([s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' for s in sentence.split()])

print(pig_latin("convert all the words"))

输出:

onvertcay allay hetay ordsway

您还可以将当前方法保留在函数转换单个单词的位置,并使用map()

>>> def pig_latin_word(s):
...   return s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay'
...
>>> ' '.join(map(pig_latin_word, "convert all the words".split()))
'onvertcay allay hetay ordsway'
>>>

答案 1 :(得分:2)

将字符串转换为字符串列表:

words = pig.split(' ')

然后你会在列表上运行for循环:

for word in words:
    #run your conversation code on each word

然后将列表重新加入字符串:

pig = ' '.join(words)