简体   繁体   中英

Python string formatting - Possible use of lambda?

I'm doing some formatted table printing, and I was wondering how i could do something like this, I think it's a situation for lambda, but I've never used it before so I'm not sure :)

print "{:^{}}|"*(self.size).format(for i in range(self.size),6) 
# self size is assumed to be 5 in this example, doesn't work, something along this line is needed though

Basically, do this(below) but in a cleaner way. PS. i know the below example doesn't work, but you get my drift

print "{:^{}}" * 5 .format(humangrid[0][0],4,humangrid[0][1],4,humangrid[0][2],4,humangrid[0][3],4,humangrid[0][4],4,

Thanks!

Here's my best guess:

print '|'.join('{:^6}'.format(i) for i in range(self.size))
...
print ''.join('{:^4}'.format(i) for i in humangrid[0])

If you really want to do it with a single call to string.format() :

print '|'.join(['{:^6}'*self.size]).format(*range(self.size))
...
print ('{:^4}'*len(humangrid[0])).format(*humangrid[0])

Assuming you're trying to pring a 2d list of names in a centered tabular way, here's one way to do it:

humangrid = [
    ["john", "jacob", "jezebel"],
    ["mary", "maria", "mel"],
    ["shareen", "sean", "shiva"],
]

cell_width = max(len(y) for x in humangrid for y in x)  # get length of longest name
cell_width += 2  # optional padding

for row in humangrid:
    print "|".join(name.center(cell_width) for name in row)

Running that will give you:

   john  |  jacob  | jezebel 
   mary  |  maria  |   mel   
 shareen |   sean  |  shiva  

To change the alignment of the table, simply replace center() with ljust() or rjust() .

One can quite easily replace that to use .format() , but I find this approach a lot more readable.

this should do what you mean

print(("{:4}|"*len(humangrid[0])).format(*humangrid[0]))

The idea is just using format(*xxx) for calling format with a variable number of arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM