0

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.

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

-1

This is one way to do it:

%(myname, mykids[0], mykids[1], mykids[2])

Comments

-1

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

Comments

-1
>>> 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 '

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.