Python 字符串替换
有没有简单的方法可以把一个列表当作参数传给Python中的字符串替换呢?
比如说:
w = ['a', 'b', 'c']
s = '%s\t%s\t%s\n' % w
这就像在字典中那样使用。
3 个回答
1
其实没必要用元组来代替列表,因为字符串的 join 方法可以直接用列表来生成字符串。
w = ['a', 'b', 'c']
'\t'.join(w) + '\n' # => 'a\tb\tc\n'
5
用元组代替列表
w = ('a', 'b', 'c')
s = '%s\t%s\t%s\n' % w
使用字典也可以
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
11
只需要把列表转换成元组就可以了:
w = ['a', 'b', 'c']
s = '%s\t%s\t%s\n' % tuple(w)