-1

Spoiler alert if you are doing code wars and haven't completed 5kyu Simple Pig Latin kata

All you must do here is:

"Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched"

For example for input 'Pig latin is cool' it should return 'igPay atinlay siay oolcay' and for 'This is my string' it should return 'hisTay siay ymay tringsay'

I tried to do a one-liner solution and my code returns syntax error when I run it and I have no idea why.

def pig_it(text):
    return ' '.join([word[1:] + word[0] + 'ay' for word in text.split() if word not in ',!?' else word])

The problem is with else word, my code doesn't build at all, why is this else statement causing a problem?

My code works fine when it looks like this

def pig_it(text):
    return ' '.join([word[1:] + word[0] + 'ay' for word in text.split() if word not in ',!?'])

It doesn't solve all tests though (whenever there is a comma, question mark or exclamation mark)

Lemaul
  • 25
  • 5
  • 1
    Please add an example input and the error that you saw; the reader cannot always guess how the code might be broken. – navneethc Jul 25 '20 at 12:50
  • By the way, `[''.join([word[1:], word[0], 'ay']) if word ...` as a [best practice](https://stackoverflow.com/questions/39675898/is-python-string-concatenation-bad-practice) – user70 Jul 25 '20 at 13:16

2 Answers2

1

word[1:] + word[0] + "ay" if word not in ",!?" else word This is a conditional expression also know as Ternary Operators and you must put expression at the left of a for loop statement and if condition at the right side of a for loop statement in a list comprehension.

return " ".join(
    [word[1:] + word[0] + "ay" if word not in ",!?" else word for word in text.split()]
)
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
0
def pig_it(text):
     return " ".join([word[1:] + word[0] + "ay" if word[0:1] not in ",!?" else word for word in text.split()])
print(pig_it('?hello, world!'))
print(pig_it('hel?lo, ?world!'))

Is this your desired output? In case YES, since you need to remain puncts untouched, you have to add more if else statements for the word[0] and word[-1] if they are in ",?!" then pass the function to word[1] and word[-2]. What I did is a demo only.

?hello, orld!way
el?lo,hay ?world!