-3

type error when sprintf list into string with python2 on linux

x = [ 'aa', 'bbbb', 'ccccccc' ]
f = '%-10s%-10s%-10s'
s = f % x

TypeError: not enough arguments for format string

2
  • 5
    Make a tuple from x: f % tuple(x) Commented Sep 16, 2015 at 12:21
  • 2
    @vaultah, if that's the answer, please post it as an answer :-) Commented Sep 16, 2015 at 12:22

1 Answer 1

5

The % operator requires that the right-hand operand has to be a tuple or a subclass of tupleif the format has multiple positional placeholders.

That is why you need to convert the arguments into a tuple:

>>> f % tuple(x)
'aa        bbbb      ccccccc   '

On the other hand, if you use a format string with a single right-hand value, you should be cautious as well, if you don't know the type of the value:

>>> foo = [1, 2, 3]
>>> 'The value is %s' % foo
'The value is [1, 2, 3]'
>>> foo = (1, 2, 3)
>>> 'The value is %s' % foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

Thus if you do not know the type of the single argument, you should always wrap it into a 1-tuple:

>>> foo = (1, 2, 3)
>>> 'The value is %s' % (foo,)
'The value is (1, 2, 3)'

That is why it is now better to use the new str.format (PEP 3101) especially for complex strings, as it is more powerful, and less prone to errors:

>>> x = ['aa', 'bbbb', 'ccccccc']
>>> '{:10}{:10}{:10}'.format(*x)
'aa        bbbb      ccccccc   '
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.