我想使用字符串格式化将变量值插入mystring,其中一些变量是正常值,一些是列表值。
myname = 'tom'
mykids = ['aa', 'bb', 'cc']
mystring = """ hello my name is %s and this are my kids %s, %s, %s """
% (myname, tuple(mykids))
我得到错误的参数不够,因为我可能错了tuple(mykids)
。帮助赞赏。
答案 0 :(得分:4)
您可以改为使用str.format()
:
>>> 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
请注意使用*mykids
解包列表并将每个列表项作为单独的参数传递给format()
。
但请注意,格式字符串是硬编码的,只能接受3个孩子。更通用的方法是将列表转换为包含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
后一种方法也适用于字符串插值:
>>> 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
最后,您可能想要处理只有一个孩子的情况:
>>> 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
答案 1 :(得分:-1)
这是一种方法:
%(myname, mykids[0], mykids[1], mykids[2])
答案 2 :(得分:-1)
这是另一种可能的方式,
在python 2.7.6
这有效:
myname = 'Njord'
mykids = ['Jason', 'Janet', 'Jack']
print "Hello my name is %s and these are my kids,", % myname
for kid in kids:
print kid
答案 3 :(得分:-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 '