質問

I need to print a line like

Device       Size     Calculated       Status

I do it so

dev =  "Device"
size = "Size"
calc = "Calculated"
stat = "Status"
print "%s%(15-x1)%s%(15-x2)%s%(15-x3)%s" % (dev, size, calc, stat)

x1 x2 x3 then the number of spaces. but i get an error:

File "<stdin>", line 1, in <module>
TypeError: format requires a mapping

how to write this command ?

役に立ちましたか?

解決

It's more simple than you think:

 print "%-15s %-15s %-15s %-15s" % (dev, size, calc, stat)

The 15 says "This string needs to be 15 characters wide in the output." - says: "Pad it on the right with spaces if necessary." Without the -, the values would be padded on the left.

他のヒント

You could also use format like this as well

print "{1: <{0}}{2: <{0}}{3: <{0}}{4}".format(15, dev, size, calc, stat)

I would use str.ljust for this:

 print "".join(map(lambda s: s.ljust(15), (dev, size, calc, stat)))

The advantage of this is that the column width is now only in one place (although this may not be an advantage if you later decide they should be different widths!)

I honestly implemented what you are saying. Here is my code.

import re

def myFormat(string):
    for i in re.finditer(r"%([(][^)]*[)])", string):
        string = re.sub(re.escape(i.group(0)), " "*eval(i.group(1)), string)
    return string

dev, size, calc, stat =  "Device", "Size", "Calculated", "Status"
x1, x2, x3 = 3, 6, 10
print myFormat("%s%(15-x1)%s%(15-x2)%s%(15-x3)%s")%(dev, size, calc, stat)

output:

'Device            Size         Calculated     Status'

UPDATE:

Why "TypeError: format requires a mapping" occur?

Python allows to write expression as below.

print "%(something)d"%{"something":123}
print "%(something)s"%{"something":"abc"}

So the part of your code, ie:

"%s%(15-x1)..."%(dev,...)
   --------      --------
      |             ^
      |             |
      +-------------+
Python interpreter expect {'15-x1':xxx, ...} here.

This is the cause of the error.

So following code raises no error. But it's output is nonsense.

"%s%(15-x1)%s%(15-x2)%s%(15-x3)%s"%{'15-x1':"abc", '15-x2':"def", '15-x3':"ghi"}

If you use %(something) in string and want to format it by using %, you need to use dict. Otherwise error TypeError: format requires a mapping occur.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top