Search code examples
pythonstringpython-2.7median

How to find median character of a string in Python 2.7


A median letter in a word is the letter present in the middle of the word and if the word length is even the middle letter is the left one out of the two middle letters.

For example , consider "apple" . The program should return 'p'.

As another example , consider "baba" . The program should return 'a'.

Also , i would like to ask if statistics.median in python would be able to do it .(i don't know if it works on strings as well as I'm new to python programming)

Please prefer to answer in python 2.7 as I'm more comfortable in python 2.7 compared to python 3 , though any help is welcome .

Thanks :D


Solution

  • Python strings are list of characters . For example :

    a = "My String"

    print a[0] #Prints M

    print a[-1] #Prints g

    len returns the length of the string in integer

    print len(a) #Prints 9

    using this we can :

    def returnMedian(mystring):
        return mystring[(len(mystring)-1)/2]  #len returns the length of the string
    
    print returnMedian("abcde")  #prints c
    print returnMedian("baba")   #prints a