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

2 Answers 2

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$

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.