Steven Matthews
Steven Matthews

Reputation: 11325

String formatting with a list - more Pythonic solution to String formatting

So lets say I have a string of text:

"""Blah blah blah %s. And also blah blah blah %s. Oh! One more thing, blah blah blah %s!!!"""

And a list of values:

values = ['foo', 'bar', 'baz', ...]

Now, I have several variables (in my case, something like 7, though I may be able to reduce that to 3 or 4) and I want to insert them all into here, however, there are five conditional that can lead to different values for the variables (as well as a few inputs), so instead what I would like to do, is take a list, and pop it in. Normally I'd do this:

"""Blah blah blah %s. And also blah blah blah %s. Oh! One more thing, blah blah blah %s!!!""" % (VariableA, VariableB, VariableC)

Is it possible, in a relatively simple way, to use a list of values instead?

I am trying to come up with a more Pythonic way for string formatting than setting multiple variables in multiple if conditions

Upvotes: 1

Views: 1008

Answers (2)

Maria Zverina
Maria Zverina

Reputation: 11173

Also don't forget about python templates:

d = {'foo':"F.O.O", 'bar':'BAR'}
Template('$foo and $bar').substitute(d)

Gives:

'F.O.O and BAR'

Upvotes: 0

Blender
Blender

Reputation: 298512

With .format(), you can expand the list so that its values are arguments for the function:

>>> vars = [1, 2, 3, 4]
>>> print '{} {} {} {}'.format(*vars)
1 2 3 4

As @TryPyPy pointed out, the equivalent syntax using the old-style string formatting would be:

>>> vars = [1, 2, 3, 4]
>>> print '%s %s %s %s' % tuple(vars)
1 2 3 4

Upvotes: 8

Related Questions