1.问题描述
2.代码
3.总结
一、问题描述:
Description:
Move the first letter of each word to the end of it, then add 'ay' to the end of the word.
Example:
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
二、代码:
** My solution **
def pig_it(text):
words = text.split(' ')
allWords = ' '.join([i[1:] + i[0] + 'ay' for i in words if i.isalpha()])
result = allWords
if not words[-1].isalpha():
result = ' '.join([allWords,words[-1]])
return result
这里面一定要注意判断标点符号,要熟练掌握 列表推导式,看看codewars上大神是怎样实现的
** Other Solutions **
- Best Practices
def pig_it(text):
lst = text.split()
return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst])
- Re
import re
def pig_it(text):
return re.sub(r'([a-z])([a-z]*)', r'\2\1ay', text, flags=re.I)
- punctuation
from string import punctuation
def pig_it(text):
words = text.split(' ')
return ' '.join(
[
'{}{}ay'.format(
word[1:],
word[0]
) if word not in punctuation else word for word in words
]
)