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
  • 5,061
  • 6
  • 46
  • 92

2 Answers2

6

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

>>> print "{:{width}}{}".format("test", "string", width=10)
test      string
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
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
  • 81,265
  • 12
  • 120
  • 179
  • 3
    This is overkill. Even the old string formatting format allows for dynamically set widths; The `*` in `'%-*s %s' % (w, 'test', 'string')` takes `w` for the width. – Martijn Pieters Dec 10 '14 at 12:22
  • @MartijnPieters great job. `'%-*s` is exactly the syntax I've been trying so hard to remember. – idanshmu Dec 10 '14 at 12:24