# StringForm with named arguments

StringForm with named arguments

In python, this is possible:

example:

a = "{x}, {y}".format(x=5, y=12)
print(a)


result:

5, 12

In Mathematica, I used

StringForm [",",5,12]


but I couldn't use named arguments.

Is there any way to do this in Mathematica? like a :

StringForm ["x,y",x->5, y->12]

• StringTemplate[" x , y"][<|"x" -> 1, "y" -> 2|>] or TemplateApply["a,b", <|"a" -> 1, "b" -> 2|>]?
– kglr
Commented May 30, 2018 at 14:08
• You may want to look at this question. Commented May 30, 2018 at 14:37

sfWithNamedArguments = TemplateApply[#, Association[MapAt[SymbolName,{##2}, {All, 1}]]]&;

sfWithNamedArguments["q,r", q -> 10, r -> 5]


"10,5"

The following also works in version 9 (where TemplateApply is not available):

ClearAll[sF]
sF = StringReplace[#, "" ~~ a_ ~~ "" :> IntegerString[ToExpression[a] /. {##2}]] &;

sF["x then y then x again", x -> 5, y -> 12]


"5 then 12 then 5 again"

Mathematica and python don't have much in common in the area you are asking about. You might consider

 Row[{x, ", ", y}] /. {x -> 5, y -> 12}


which displays as

but is not a string.

% // FullForm


FullForm[Row[{5, ", ", 12}]]

If you need a string rather than a display form, use

(Row[{x, ", ", y}] /. {x -> 5, y -> 12}) // ToString