2
$\begingroup$

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]
$\endgroup$
2
  • 5
    $\begingroup$ StringTemplate[" `x` , `y`"][<|"x" -> 1, "y" -> 2|>] or TemplateApply["`a`,`b`", <|"a" -> 1, "b" -> 2|>]? $\endgroup$
    – kglr
    Commented May 30, 2018 at 14:08
  • 1
    $\begingroup$ You may want to look at this question. $\endgroup$
    – rhermans
    Commented May 30, 2018 at 14:37

3 Answers 3

2
$\begingroup$
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"

$\endgroup$
1
$\begingroup$

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

row

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
$\endgroup$
1
$\begingroup$

I think the idiomatic way to write "{x}, {y}".format(x=5, y=12) in Wolfram Language would be

In[72]:= StringTemplate["`x`,`y`"][<|"x" -> 5, "y" -> 12|>]

Out[72]= "5,12"

edit: I posted this because I didn't see StringTemplate in either of the answers, but looking now I see it was in a comment-as-answer. I will leave it up nonetheless.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.