hyperboreean
hyperboreean

Reputation: 8343

python string substitution

Is there a simple way of passing a list as the parameter to a string substitution in 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.

Upvotes: 9

Views: 13288

Answers (3)

Garren S
Garren S

Reputation: 5782

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'

Upvotes: 1

Fabian Barkhau
Fabian Barkhau

Reputation: 1357

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

Upvotes: 5

Amnon
Amnon

Reputation: 7772

Just convert the list to a tuple:

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

Upvotes: 11

Related Questions