【问题标题】:Function in python that justifies string (to either left, center or right)python中证明字符串的函数(向左、居中或向右)
【发布时间】:2015-06-18 00:24:31
【问题描述】:

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

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

【问题讨论】:

  • 它实际上是做什么的?错误?我自己会使用“%-70s”和“%70s” sprintf 风格的面具,它们更干净。中心证明可能可以通过一些额外的工作来实现
  • @BrenBarn 谢谢 :)

标签: python string function formatting justify


【解决方案1】:

您在第二个 elif 中错过了一个括号。更正下面的代码 -

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

【讨论】:

    【解决方案2】:
    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                                 :
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 2013-05-01
      • 2011-03-29
      • 1970-01-01
      • 2013-09-01
      • 2019-04-11
      相关资源
      最近更新 更多