David Villasmil
David Villasmil

Reputation: 415

Python format string

I have this array:

rows = ['1393586700', 'BLAHBLAH', 'BLEHBLEH', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '0', '0']

and this format String:

format String:   """%s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s"""

and this fails:

print 'test: ', formatStr % rows

    print 'test: ', formatStr % rows

TypeError: not enough arguments for format string

Why is it failing? there are exactly the same number of %s and fields!

Thanks!

Upvotes: 0

Views: 260

Answers (3)

Dmitry Zagorulkin
Dmitry Zagorulkin

Reputation: 8548

You should pass the tuple instead of the list

>>> rows = ['1393586700', 'BLAHBLAH', 'BLEHBLEH', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '0', '0']
>>> f = """%s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s ,  %s"""
>>>
>>> f % tuple(rows) 

'1393586700 ,  BLAHBLAH ,  BLEHBLEH ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  1 ,  1 ,  0 ,  0'
    >>>

Upvotes: 1

mockinterface
mockinterface

Reputation: 14860

This happens because you are printing a list instead of the expected tuple.

Observe this,

>>> print """%s %s""" % [1, 2]
TypeError: not enough arguments for format string

vs.,

>>> print """%s %s""" % (1, 2)
1 2

converting list to a tuple can be done with the tuple() function:

>>> print """%s %s""" % tuple([1, 2])
1 2

Upvotes: 3

msvalkon
msvalkon

Reputation: 12077

Use str.join

>>> rows = ['1393586700', 'BLAHBLAH', 'BLEHBLEH', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '1', '1', '0', '0']
>>> 
>>> ", ".join(rows)
'1393586700, BLAHBLAH, BLEHBLEH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0'

Upvotes: 0

Related Questions