1

So I have this simple print statement:

print "%-10s %s" % ("test","string")

which prints the desired output:

test       string

I'm trying to figure out the correct syntax for a case where the fill value is a variable. Example:

w = 10
print "%-s %s" % (w,"test","string")

So %-s should be replaced with what to accommodate the fill value?

If I remember it correctly, the syntax is similar to %-xs where x is replaced by a an int variable. I might be mistaken though.

Note

I know this question is probably duplicated since this is really elementary string formatting issue. However, after some time of searching for the right syntax I gave up.

Community
  • 1
  • 1
idanshmu
  • 4,891
  • 5
  • 43
  • 83

2 Answers2

6

I would be inclined to use str.format, instead:

>>> print "{:{width}}{}".format("test", "string", width=10)
test      string
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
0

You could do this in two stages: First, create the proper format string, then use it to create the actual output. Use %d as a placeholder for the width and escape each other % as %%.

formatstring = "%%-%ds %%s" % w
print formatstring % ("test","string")

Or in one line:

print ("%%-%ds %%s" % w) % ("test","string")

Update: As pointed out by Martijn in the comments, you can also use * in the format string:

print "%-*s %s" % (w,"test","string")

From the documentation:

Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

tobias_k
  • 78,071
  • 11
  • 109
  • 168