猪拉丁编码

Pig Latin coding

我正在做某事,但似乎无法获得执行我需要的代码 -- 我看到了以下代码:

def pig_latin(string):
vowels = ['a', 'e', 'o', 'i', 'u']
if string[0] in vowels:   #if the first letter is vowel 
    return string + 'ay' 
elif string[1] in vowels: #if the first letter is consonant
    return string[1:] + string[0] + 'ay'
elif string[2] in vowels: #if first two letters are consonants
    return string[2:] + string[:2] + 'ay'
else: #if the first three letters are consonants
    return string[3:] + string[:3] + 'ay'

有了这个,我应该将我的字符串“the empire strikes back”修改为“ethay empireay ikesstray ackbay”。我能够更改代码以至少返回“empireay”(并忘记了具体如何)但其余部分没有成功。我在这里没有看到什么?

你的代码似乎对一个词有效 - 你只需要为句子中的所有词调用它:

def pig_latin(string):
  vowels = ['a', 'e', 'o', 'i', 'u']
  if string[0] in vowels:   #if the first letter is vowel 
      return string + 'ay' 
  elif string[1] in vowels: #if the first letter is consonant
      return string[1:] + string[0] + 'ay'
  elif string[2] in vowels: #if first two letters are consonants
      return string[2:] + string[:2] + 'ay'
  else: #if the first three letters are consonants
      return string[3:] + string[:3] + 'ay'

string = "the empire strikes back"
parts = string.split(" ")
pig_latin_parts = [pig_latin(part) for part in parts]
print(" ".join(pig_latin_parts)) // prints "ethay empireay ikesstray ackbay"