繁体   English   中英

python字符串替换

[英]python string substitution

有没有一种简单的方法将列表作为参数传递给python中的字符串替换? 就像是:

w = ['a', 'b', 'c']

s = '%s\\t%s\\t%s\\n' % w

类似于字典在这种情况下的工作方式。

只需将列表转换为元组:

w = ['a', 'b', 'c']
s = '%s\t%s\t%s\n' % tuple(w)

使用元组而不是列表

w = ('a', 'b', 'c')
s = '%s\t%s\t%s\n' % w

使用dict也有效

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

当字符串的连接可以使用列表为您构建字符串时,不必使用元组而不是列表。

w = ['a', 'b', 'c'] '\\t'.join(w) + '\\n' # => 'a\\tb\\tc\\n'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM