9

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.

3 Answers 3

11

Just convert the list to a tuple:

w = ['a', 'b', 'c']
s = '%s\t%s\t%s\n' % tuple(w)
Sign up to request clarification or add additional context in comments.

2 Comments

And of course, as fabe said, you can just use a tuple directly.
It depends from where that data is coming from :-), but yes, theoretically it's possible.
5

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

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.