问题
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.
回答1:
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
回答2:
This is one way to do it:
%(myname, mykids[0], mykids[1], mykids[2])
回答3:
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
回答4:
>>> 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 '
来源:https://stackoverflow.com/questions/31822396/python-string-format-with-both-list-and-string