pdubois
pdubois

Reputation: 7790

Printing list into fixed width strings in Python

With the following list"

In [3]: entr = [ 'ATOM', '1', 'P', 'C', 'B', '3', '42.564', '-34.232', '-7.330', '1.00', '105.08', 'P' ]

I'd like to create a string with fixed width using %. But why this failed? Both lines contain 12 entries.

In [4]: buf = "%-6s%5d  %-4s%3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f          %2s\n" % entr
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-6c71c289664e> in <module>()
----> 1 buf = "%-6s%5d  %-4s%3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f          %2s\n" % entr

TypeError: not enough arguments for format string

Upvotes: 1

Views: 2439

Answers (5)

Zioalex
Zioalex

Reputation: 4303

With the .format operator you can do:

entr = [ 'ATOM', '1', 'P', 'C', 'B', '3', '42.564', '-34.232', '-7.330', '1.00', '105.08', 'P' ]

print(['{0: <6}'.format(str(x)) for x in entr])
['ATOM  ', '1     ', 'P     ', 'C     ', 'B     ', '3     ', '42.564', '-34.232', '-7.330', '1.00  ', '105.08', 'P     ']

Upvotes: 1

cengizkrbck
cengizkrbck

Reputation: 704

First you should give a tuple to format operator %

"..." % tuple(entr)

Second, you should use %d for numbers, not strings! So, you need to cast this variables to number. Here is the short example;

"...%s ... %d ... %f " %(entr[1], float(entr[2]), float(entr))

Upvotes: 1

Klaus D.
Klaus D.

Reputation: 14369

Your dataset fields are all strings, you can notuse number formating in them. They have to be convertet to number type, also to use the %-formatting the argument has to be a tuple, not a list.

entr = ('ATOM', 1, 'P', 'C', 'B', 3, 42.564, -34.232, -7.330, 1.00, 105.08, 'P')

Upvotes: 1

Antoine
Antoine

Reputation: 1070

1) The %operator expect a tuple, you give a list.

2) All item in your list are strings, In you format, you use decimal and float specifier. You should cast the item in your list to the proper type.

Upvotes: 1

Ohumeronen
Ohumeronen

Reputation: 2086

Ok I think you could use this:

entr = [ 'ATOM', '1', 'P', 'C', 'B', '3', '42.564', '-34.232', '-7.330', '1.00', '105.08', 'P' ]
buf = "{}-6s{}5d  {}-4s{}3s {}1s{}4d    {}8.3f{}8.3f{}8.3f{}6.2f{}6.2f          {}2s\n".format(*entr)
print buf

Is that good?

Upvotes: 1

Related Questions