1

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

3
  • 1
    Since tuple(listofvalues) would trivially work, I assume you mean something more complex. Can you explain what "so instead what I would like to do, is take a list, and pop it in" means? Have you considered using named fields and a dictionary? Commented May 30, 2012 at 20:53
  • Question is very unclear. What is a "list of values" and how is it different from the example? Commented May 30, 2012 at 20:55
  • 1
    Can you show us what "setting multiple variables in multiple if conditions" looks like? Commented May 30, 2012 at 20:58

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

0

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'

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.