python string substitution
Is there a simple way of passing a list as the parameter to a string substitution in开发者_Go百科 python ? Something like:
w = ['a', 'b', 'c']
s = '%s\t%s\t%s\n' % w
Something similar to the way dictionaries work in this case.
Just convert the list to a tuple:
w = ['a', 'b', 'c']
s = '%s\t%s\t%s\n' % tuple(w)
use a tuple instead of a list
w = ('a', 'b', 'c')
s = '%s\t%s\t%s\n' % w
using a dict also works
w = { 'Akey' : 'a', 'Bkey' : 'b', 'Ckey' : 'c' }
s = '%(Akey)s\t%(Bkey)s\t%(Ckey)s\n' % w
http://docs.python.org/release/2.5.2/lib/typesseq-strings.html
It's unnecessary to use a tuple instead of a list when string's join can build the string using a list for you.
w = ['a', 'b', 'c']
'\t'.join(w) + '\n' # => 'a\tb\tc\n'
精彩评论