Reputation: 143
As I am just a beginner, I made a small single-word Pig Latin translator in Python 3.5. I have my rough code that works, however I'd really like your opinions on how to make it more compact, pythonic, and "elegant" (i.e.-professional). Any help is appreciated, thank you!
#Converts a word into pig latin, needs to be cleaned up
def pig_latin(word):
word = list(word)
first_letter = word[0]
del word[0]
word.insert(len(word),first_letter)
word.insert(len(word),'ay')
print(''.join(word))
Upvotes: 2
Views: 153
Reputation: 476709
You do not need to convert the string to a list, do some magic with it and convert it back: if you apply [1:]
on a string, you get the string without the first character. So you can easily translate it into:
def pig_latin(word):
print('%s%say'%(word[1:],word[0]))
or equivalently:
def pig_latin(word):
print('{}{}ay'.format(word[1:],word[0]))
Here we use string formatting: so we replace '%s%say'
in such way that the first %s
is replaced with word[1:]
, and the second with word[0]
followed by an 'ay'
.
This generates:
>>> pig_latin('foobar')
oobarfay
Upvotes: 2