Wednesday, February 21, 2024
HomeSoftware EngineeringGet the Center Character in Python

Get the Center Character in Python


The problem

Return the center character of the phrase. If the phrase’s size is odd, return the center character. If the phrase’s size is even, return the center 2 characters.

Examples:

getMiddle("check") # ought to return "es"
getMiddle("testing") # ought to return "t"
getMiddle("center") # ought to return "dd"
getMiddle("A") # ought to return "A"

Enter

A phrase (string) of size 0 < str < 1000 (In javascript chances are you’ll get barely greater than 1000 in some check circumstances as a result of an error within the check circumstances). You don’t want to check for this. That is solely right here to let you know that you don’t want to fret about your resolution timing out.

Output

The center character(s) of the phrase is represented as a string.

The answer in Python code

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

Choice 2:

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

Choice 3:

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

Take a look at circumstances to validate our resolution

check.assert_equals(get_middle("check"),"es")
check.assert_equals(get_middle("testing"),"t")
check.assert_equals(get_middle("center"),"dd")
check.assert_equals(get_middle("A"),"A")
check.assert_equals(get_middle("of"),"of")
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments