How can I pass a tuple to str.format()?
Asked Answered
P

2

0

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    '
>>>> "{!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'm passing a tuple with two elements, which is than passed on to the function as a tuple with one element, my original tuple. Hence this error. so the question is rather how to pass this tuple to the format function...

Preston answered 27/4, 2015 at 6:27 Comment(0)
C
6

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

>>> "{!s:4}{!s:5}".format(*b)
'j   4    '
Cirrhosis answered 24/3, 2016 at 12:27 Comment(0)
A
0

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.

Amir answered 24/3, 2016 at 12:3 Comment(1)
It also works in Python 2.x. You are only trying to print one value {0}, and that's what you get - the value of b. "{0}, {1}".format(b) fails (as does "{1}".format(b)). This doesn't answer OP's question.Sheik

© 2022 - 2024 — McMap. All rights reserved.