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
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 '
x:f % tuple(x)