I am puzzled why I can assign/unpack the return of split() to the
appropriate number of variables, but the same fails for use in a
print string using formatting directives.
E.g., given:
In [202]: s
Out[202]: 'here are 4 values'
In [203]: s.split()
Out[203]: ['here', 'are', '4', 'values']
This works as expected:
In [204]: a, b, c, d = s.split()
In [205]: print '%s %s %s %s' % (a, b, c, d)
here are 4 values
But this fails ..
In [206]: print '%s %s %s %s' % (s.split())
I am not sure why? Shouldn’t the return of split() be
unpacked and be distributed over the expected arguments for the
formatting strings?
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
C:\bla\Desktop\<ipython-input-206-600f130ff0b2> in <module>()
----> 1 print '%s %s %s %s' % (s.split())
TypeError: not enough arguments for format string
“Note enough arguments” .. I do have the right number of items in the list. Does the list for some reason not unpack in this case, but does with assignments to variables?
I came across this in attempting to answer this question
writing column entry just one below another in python
You must convert
s.split()into a tuple like sofor formatting or use
.format()instead, unpacking the arguments.