5
$\begingroup$

I am trying to join together strings and variables as part of formatting the output of my code. For example how do I print the line "5 trees" where the number 5 is a variable n that could be changing. I've tried the following, which doesn't work:

 n=5;
 Print[n <> "trees"]

Any idea on how to get that to print as "5 trees"? Thanks!

$\endgroup$
1
  • 1
    $\begingroup$ Print[n, " trees"] and take a look StringForm or Templates friends. $\endgroup$ – Kuba Apr 2 '15 at 19:55
8
$\begingroup$

For trivial combinations, simple Print combinations work well.

For more complex operations, take a look at StringForm:

var1 = "Tree";
var2 = 10;

StringForm["The `1` is about `2` feet tall...", var1, var2]

(* "The Tree is about 10 feet tall..." *)
$\endgroup$
5
$\begingroup$
n = 5;
Print[ToString[n] <> " trees"]
$\endgroup$

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