user1886376
user1886376

Reputation:

How to print the spaces between variables?

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 ?

Upvotes: 1

Views: 243

Answers (4)

Kei Minagawa
Kei Minagawa

Reputation: 4511

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.

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122032

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!)

Upvotes: 3

sagarchalise
sagarchalise

Reputation: 1020

You could also use format like this as well

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

Upvotes: 3

Aaron Digulla
Aaron Digulla

Reputation: 328604

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.

Upvotes: 3

Related Questions