# Return a sentence with numerical values

I have the following function:

example[a_, b_] :=
Module[{c},
c = a + b;
Return["The solution is c"]
]


I would like to know how to return that sentence but with the actual value of c. For example, if I write example[x, x+1], I want to obtain "The solution is 2x+1".

Old versions:

Use StringForm[]:

example[a_, b_] := Module[{c = a + b},
ToString[StringForm["The solution is ", c]]]

example[x, x + 1]
"The solution is 1 + 2 x"


New versions:

Use StringTemplate[]:

example[a_, b_] := Module[{c = a + b},
StringTemplate["The solution is sol"] @
<|"sol" -> ToString[c, StandardForm]|>]

example[x, x + 1]
"The solution is 1 + 2 x"


(The actual output contains RowBox objects within the string.)

Apart from StringForm["The solution is ", c], another solution is using StringJoin[](<>) directly.

example[a_, b_] :=
Module[{c}, c = a + b;
"The solution is " <> ToString[c]
]


Or

example[a_, b_] := "The solution is " <> ToString[a + b]


If you want to keep the format separate form the function (could be useful in situations where you have many functions like example you want to format like this.

Define an UpValue solution that uses TextString

solution /: TextString[solution[s_]] :=
"The solution is " <> ToString[s // TraditionalForm]


Now using this definition for example:

example[a_, b_] := Module[{c}, c = a + b]

TextString[solution@example[x, x + 1]]
(* "The solution is 2 x + 1" *)


With a new example2 we can use solution again:

example2[a_, b_] :=
Module[{c}, c = Integrate[Sin[a x + b], {x, 0, 2 Pi}]]

TextString[solution@example2[a, b]]

(* "The solution is \!$$\*FormBox[FractionBox[\(2\\\ \ \(sin(π\\\ a)$$\\\ $$sin(π\\\ a + b)$$\), $$a$$],