freezed
freezed

Reputation: 1339

Correct syntax when using tuple with str.format()

I have some troubles affecting tuple values to a str.format() method like this:

tpl = ("alpha", "omega")
msg = "From {} to {} "
print(msg.format(tpl))

Python gives me an tuple index out of range error and numbered curly brace can't solve it.

Upvotes: 0

Views: 98

Answers (3)

nsaura
nsaura

Reputation: 331

I don't have the answer to your question, but I can provide you an alternative way of doing.

It looks like you want to define a generic message whose content can vary throughout your process. Then, you can use lambda function. Here is an example :

m = lambda X : "from {} {} {}".format(X[0], X[1], X[2])
inputs = ["alpha", "to", "omega"]
scd_inputs = [1, "to", 5]
print m(inputs)
>>> "from alpha to omega"
print m(scd_inputs)
>>> "from 1 to 5"

That is, if I understood well, what you want.

In this example I assumed you have constructed a list of inputs, but you can also use m = lambda s1, s2, s3: "From {} {} {}".format(s1 s2 s3) that you call like this : m(first_arg, scd, third)

I hope it can help

Upvotes: 1

allo
allo

Reputation: 4236

You are calling format with one argument (which is a tuple), while it expects being called with two. It does not automatically unpack tuples and lists.

But you can give format a tuple/list by using it for its *args parameter:

tpl = ("alpha", "omega")
msg = "From {} to {} "
print(msg.format(*tpl))

You can do so for **kwargs as well:

params = {"a": 1, "b": 2}
print("{a} {b}".format(**params))

Upvotes: 1

freezed
freezed

Reputation: 1339

I made a script for finding and testing different syntax. I'm glad to discover that I can mix it with named argument too.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" format syntax with tuple"""

t = ("alpha", "omega")
v = "to"

m = "From {} {} {} "
ms = "From {0} to {1}"
msg = "From {0} {var} {1} "

expr_list = [
    "t, v",
    "m.format(t, v)",
    "m.format(*t, v)",
    "ms.format(t)",
    "msg.format(t, v)",
    "msg.format(t, var=v)",
    "msg.format(*t, var=v)",
]

for num, expr in enumerate(expr_list):
    try:
        print("Expr{}, <{}>: «{}»".format(num, expr, eval(expr)))
    except Exception as except_detail:
        print("Expr{}, <{}> : Exception «{}»".format(num, expr, except_detail))

It returns:

Expr0, <t, v>: «(('alpha', 'omega'), 'to')»
Expr1, <m.format(t, v)> : Exception «tuple index out of range»
Expr2, <m.format(*t, v)> : Exception «only named arguments may follow *expression (<string>, line 1)»
Expr3, <ms.format(t)> : Exception «tuple index out of range»
Expr4, <msg.format(t, v)> : Exception «'var'»
Expr5, <msg.format(t, var=v)> : Exception «tuple index out of range»
Expr6, <msg.format(*t, var=v)>: «From alpha to omega »

Upvotes: 0

Related Questions