How to pass a tuple to str.format ()?

I am trying to use the str.format() function to print a matrix in columns.

This is the line that goes wrong:

 >>>> "{!s:4}{!s:5}".format('j',4,3) 'j 4 ' >>>> "{!s:4}{!s:5}".format(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range >>> b ('dat', 'is') 

What am I doing wrong?

Edit: I think I know what the problem is: I pass a tuple with two elements, which is passed to the function as a tuple with one element, my original tuple. Hence this error. so the question is how to pass this tuple to a format function ...

0
source share
2 answers

You can unpack a tuple if you can be sure of its length.

 >>> "{!s:4}{!s:5}".format(*b) 'j 4 ' 
0
source

EDIT: Sorry, I answered your question too soon before I fully understood it. I think you want to unpack the tuple, just like in the answer prog.

Depending on which version of Python you are using, a little depends. The following steps are for Python 3.5 (and probably all of Python 3).

The code:

 b = ("dat", "is") "{0}".format(b) 

Output:

 "('dat', 'is')" 

Also check out Python docs on string formatting .

-one
source

All Articles