Reputation: 8025
I want to use string formatting to insert variable values into mystring where some of the variables are normal values and some are list values.
myname = 'tom'
mykids = ['aa', 'bb', 'cc']
mystring = """ hello my name is %s and this are my kids %s, %s, %s """
% (myname, tuple(mykids))
I get the error not enough arguments because i probably did the tuple(mykids)
wrong. help appreciated.
Upvotes: 0
Views: 89
Reputation: 87054
You can use str.format()
instead:
>>> myname = 'tom'
>>> mykids = ['aa','bb','cc']
>>> mystring = 'hello my name is {} and this are my kids {}, {}, {}'.format(myname, *mykids)
>>> print mystring
hello my name is tom and this are my kids aa, bb, cc
Note the use of *mykids
which unpacks the list and passes each list item as a separate argument to format()
.
Notice, however, that the format string is hardcoded to accept only 3 kids. A more generic way is to convert the list to a string with str.join()
:
>>> mystring = 'hello my name is {} and this are my kids {}'.format(myname, ', '.join(mykids))
>>> print mystring
hello my name is tom and this are my kids aa, bb, cc
>>> mykids.append('dd')
>>> mystring = 'hello my name is {} and this are my kids {}'.format(myname, ', '.join(mykids))
>>> print mystring
hello my name is tom and this are my kids aa, bb, cc, dd
The latter method also works with string interpolation:
>>> mystring = 'hello my name is %s and this are my kids %s' % (myname, ', '.join(mykids))
>>> print mystring
hello my name is tom and this are my kids aa, bb, cc, dd
Finally you might want to handle the case where there is only one child:
>>> one_kid = 'this is my kid'
>>> many_kids = 'these are my kids'
>>> mystring = 'hello my name is {} and {} {}'.format(myname, many_kids if len(mykids) > 1 else one_kid, ', '.join(mykids))
>>> print mystring
hello my name is tom and these are my kids aa, bb, cc, dd
>>> mykids = ['aa']
>>> mystring = 'hello my name is {} and {} {}'.format(myname, many_kids if len(mykids) > 1 else one_kid, ', '.join(mykids))
>>> print mystring
hello my name is tom and this is my kid aa
Upvotes: 4
Reputation: 3039
>>> mystring=" hello my name is %s and this are my kids %s, %s, %s " %((myname,) + tuple(mykids))
>>> mystring
' hello my name is tom and this are my kids aa, bb, cc '
Upvotes: -1
Reputation: 142
This is another possible way,
In python 2.7.6
this works:
myname = 'Njord'
mykids = ['Jason', 'Janet', 'Jack']
print "Hello my name is %s and these are my kids,", % myname
for kid in kids:
print kid
Upvotes: -1
Reputation: 6589
This is one way to do it:
%(myname, mykids[0], mykids[1], mykids[2])
Upvotes: -1