c_sdow
c_sdow

Reputation: 13

Pig Latin coding

I'm working on something but can't seem to get the code to do what I need it to -- I'm presented with the following code:

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'

With this, I'm supposed to modify my string "the empire strikes back" to instead read "ethay empireay ikesstray ackbay." I was able to change the code to at least get back "empireay" (and forgot exactly how) but haven't had success with the rest. What am I not seeing here?

Upvotes: 1

Views: 97

Answers (1)

Aziz Sonawalla
Aziz Sonawalla

Reputation: 2502

You're code seems to work for one word - you just need to call it for all words in the sentence:

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"

Upvotes: 2

Related Questions