Skip to content Skip to sidebar Skip to footer

How Can I Pass A Tuple To Str.format()?

I'm 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 ' >>>

Solution 1:

You can unpack the tuple if you can be certain of its length.

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

Solution 2:

EDIT: Sorry I answered your question too soon before I fully understood it. I think you want to unpack the tuple, exactly as in progo's answer.

It depends slightly on what version of Python you're using. The following works for Python 3.5 (and probably all Python 3).

Code:

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

Output:

"('dat', 'is')"

Also check the Python docs on string formatting.

Post a Comment for "How Can I Pass A Tuple To Str.format()?"