-4

Need some help with Python string formatting
I have two code:

a = "Hello"
b = False
p = "Python rocks"
q = True

I want to print a,b,p & q like this:

Hello ................................. False
Python rocks .......................... True

The total length of each line (From Hello to False) is fixed say 70 chars.

(edit) Following was being tried. Clearly not a good way (and incorrect), hence the question

arr = [ ["Hello", False], ["Python rocks", True]]
totallen = 70

for e in arr:
    result = "{0}".format(e[1])
    dottedlen = totallen - len(e[0]) - len(result) - 2
    dottedstr = "." * dottedlen
    str = "".join([e[0], " ", dottedstr, " ", result])
    print str
4

2 回答 2

1

使用字符串格式

In [48]: def solve(a,b):
    a,b=str(a),str(b)
    spaces=len(a.split())-1
    return "{0} {1} {2}".format(a,"."*(68-len(a)-len(b)-spaces),b)
   ....: 

In [49]: print solve(a,b);print solve(p,q)
Hello .......................................................... False
Python rocks ................................................... True
于 2013-04-24T17:53:51.810 回答
0

只需创建一个函数来添加句点直到您的固定数量的字符:

def formatter(my_string,length,my_boolean):
    my_string += " " + "." * (length - len(my_string))
    print my_string, my_boolean
formatter(a,70,b)
formatter(p,70,q)

注意:使用 print 而不是 return 的原因是,当您返回然后打印它时,使用此方法会打印以下内容:

('Hello .................................................................', False)
('Python rocks ..........................................................', False)

但没有返回,直接从函数中打印它会给你你想要的:

Hello ................................................................. False
Python rocks .......................................................... False
于 2013-04-24T17:53:19.597 回答