Get the Middle Character in Python

The challenge

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.


getMiddle("test") # should return "es" getMiddle("testing") # should return "t" getMiddle("middle") # should return "dd" getMiddle("A") # should return "A"
Code language: Python (python)


A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.


The middle character(s) of the word is represented as a string.

The solution in Python code

Option 1:

def get_middle(s): if len(s)%2==0: i = int(len(s)/2)-1 return s[i]+s[i+1] else: return s[int(len(s)/2)]
Code language: Python (python)

Option 2:

def get_middle(s): return s[(len(s)-1)/2:len(s)/2+1]
Code language: Python (python)

Option 3:

def get_middle(s): i = (len(s) - 1) // 2 return s[i:-i] or s
Code language: Python (python)

Test cases to validate our solution

test.assert_equals(get_middle("test"),"es") test.assert_equals(get_middle("testing"),"t") test.assert_equals(get_middle("middle"),"dd") test.assert_equals(get_middle("A"),"A") test.assert_equals(get_middle("of"),"of")
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments