我的个人博客
更多内容,请跳转我的个人博客
题目
Simple Pig Latin
简单的猪拉丁文
描述
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.
将每个单词的第一个字母移到它的末尾,然后在单词的末尾加上“ay”。保持标点符号不变。
例子
pig_it(‘Pig latin is cool’) # igPay atinlay siay oolcay
pig_it(‘Hello world !’) # elloHay orldway !
思路
这个题的思路其实也很简单,和之前做过的一个题类似(不要扭曲我的话)。
因为不好直接对这个字符串进行操作,所以先进行拆分
然后对单个单词进行操作,这样就变得简单了,通过切片的操作,分别得到这个单词的第一个字母和字母后面的部分,然后把第一个字母加上"ay"即可
注意:因为字符串中存在"!“和”?"的情况,这里要排除,当然因为这里只有这两个符号,比较简单,如果存起其他不同的,可以通过判断是否是isalpha进行判断。
最后组合一下就好
完整代码
def pig_it(text):
#your code here
# 拆分成列表
text = text.split(" ")
# 遍历,每一个单词
for i in range(len(text)):
# 注意排除"!"?"
if text[i] != "!" and text[i] != "?":
# 得到第一个字母
first = text[i][0]
# 得到后面的字母
before = text[i][1:]
# 在第一个字母后面加上“ay””
first += "ay"
# 重新赋值
text[i] = before + first
# 最后组合在一起,这里注意需要空格。
return " ".join(text)