Get the Middle Character in Python

0 min read 173 words

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.

Examples:

getMiddle("test") # should return "es"
getMiddle("testing") # should return "t"
getMiddle("middle") # should return "dd"
getMiddle("A") # should return "A"

Input

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.

Output

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)]

Option 2:

def get_middle(s):
    return s[(len(s)-1)/2:len(s)/2+1]

Option 3:

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

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")
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags