题目:
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
#Examples:
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
my code:
def get_middle(s):
#your code here
result = ""
middle = int(len(s)//2)
if len(s) %2 ==0: #如果长度是偶数,取中间的两个字符
result = "".join(s[(middle-1):(middle+1)])
else:
result = s[middle]
return result
smart code:
def get_middle(s):
index, odd = divmod(len(s), 2) #odd为奇数,even为偶数
return s[index] if odd else s[index - 1:index + 1]