Skip to content Skip to sidebar Skip to footer

Python String Format With Both List And String

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'

Solution 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

Solution 2:


Solution 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

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

Post a Comment for "Python String Format With Both List And String"