python string format with both list and string

核能气质少年 提交于 2020-01-06 20:25:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!