Search code examples
pythonstringfunctionformattingjustify

Function in python that justifies string (to either left, center or right)


I would like to use a function in my code that would justify the string. I'm stuck please look at my code. Thanks in advance.

def justify(s, pos):      #(<string>, <[l]/[c]/[r]>)
if len(s)<=70:

    if pos == l:
        print 30*' ' + s
    elif pos == c:
        print ((70 - len(s))/2)*' ' + s
    elif pos == r:
        print (40 - len(s)*' ' + s

    else:
        print('You entered invalid argument-(use either r, c or l)')
else:
    print("The entered string is more than 70 character long. Couldn't be justified.")

Solution

  • you missed a bracket at second elif. corrected code below -

    def justify(s, pos):
        if len(s)<=70:
            if pos == l:
                print 30*' ' + s
            elif pos == c:
                print ((70 - len(s))/2)*' ' + s
            elif pos == r:
                #you missed it here...
                print (40 - len(s))*' ' + s
            else:
                print('You entered invalid argument-(use either r, c or l)')
        else:
            print("The entered string is more than 70 character long. Couldn't be justified.")