2017-02-12 120 views
2

因爲我只是一個初學者,所以我在Python 3.5中創建了一個小型單字豬拉丁語翻譯器。我有我的粗略代碼,但我真的很喜歡你的意見,如何使它更緊湊,pythonic,和「優雅」(即專業)。任何幫助表示讚賞,謝謝!在Python中「清理」基本豬拉丁語翻譯器

#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)) 
+3

那麼對於初學者'x.insert(LEN(X)中,y)'相當於'x.append(Y)'。 –

+1

添加文檔字符串,以描述輸入和預期輸出。 –

+2

由於你有工作代碼,這可能更適合於[代碼評論](http://codereview.stackexchange.com/) –

回答

2

你不需要將字符串轉換到一個列表,做一些魔術,並把它轉換回:如果你在一個字符串適用[1:],你沒有得到的第一個字符的字符串。所以,你可以很容易地把它翻譯成:

def pig_latin(word): 
    print('%s%say'%(word[1:],word[0])) 

或等價:

def pig_latin(word): 
    print('{}{}ay'.format(word[1:],word[0])) 

這裏我們使用字符串格式化:所以我們在第一%s被替換爲word[1:]這樣的方式代替'%s%say',而第二與word[0]後跟'ay'

這產生:

>>> pig_latin('foobar') 
oobarfay 
+1

我會用'.format'來更清楚你在做什麼。 –

+2

非常聰明!好主意,謝謝。 – 9voltWolfXX