python中的函数,证明字符串(左,中或右)

时间:2015-04-12 18:01:46

标签: python string function formatting justify

我想在我的代码中使用一个函数来证明字符串的合理性。我被困了,请看看我的代码。 提前谢谢。

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.")

2 个答案:

答案 0 :(得分:0)

你错过了第二名的支架。更正下面的代码 -

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.")

答案 1 :(得分:0)

def justify2(s, pos):
    di = {"l" : "%-70s", "r" : "%70s"}

    if pos in ("l","r"):
        print ":" + di[pos] % s + ":"
    elif pos == "c":
        split = len(s) / 2
        s1, s2 = s[:split], s[split:]
        print ":" + "%35s" % s1 + "%-35s" % s2 + ":"
    else:
        "bad position:%s:" % (pos)


justify2("abc", "l")
justify2("def", "r")
justify2("xyz", "c")

:abc                                                                   :
:                                                                   def:
:                                  xyz                                 :