1

How can I use string.format() in a fashion such that:

line = 'first {0}, second {1}'
print(line.format([1,2]))

would print first 1 second 2.

1
  • 1
    Note that explicitly numbering the format fields was only necessary in Python 2.6. All modern versions of Python will do it for you, so you only need: line = 'first {}, second {}' Commented Jan 21, 2015 at 3:26

1 Answer 1

4

You can unpack the list:

>>> line = 'first {0}, second {1}'
>>> l = [1, 2]
>>> print(line.format(*l))
first 1, second 2
Sign up to request clarification or add additional context in comments.

1 Comment

Naming variables l is generally best avoided to avoid confusion between I, l and 1 </pedant>

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.