Wolfram: String Template

By Xah Lee. Date: . Last updated: .

String Template (Formatting String)

StringTemplate[template][args]

Returns a string, with placeholders, that are filled by args

template is a string. In this string, the following are special:

  • `` → a placeholder.
  • `n` → nth placeholder.
  • `name` → a named placeholder. (used when the args is Association (Key Value List) )
  • <*expr*> → an expression, to be evaluated when the template is applied.
(* simple example *)
StringTemplate[ "`` plus `` is ``"][1, 2, 1 + 2]
(* 1 plus 2 is 3 *)
(* control number of digits *)
StringTemplate[ "``"][NumberForm[123.456789, 3] ]
(* 123. *)
(* embed a variable *)
x = 5;
StringTemplate[ "i have `` cats"][x]
(* i have 5 cats *)

(* embed a variable as expression. *)
StringTemplate[ "i have <*x*> cats"][]
(* i have 5 cats *)
(* StringTemplate example, fill by values from association list *)
xx = Association[ "a" -> 1, "b" -> 2, "c" -> 3];
StringTemplate[ "`a` plus `b` is `c`"][ xx ]
(* 1 plus 2 is 3 *)
(* StringTemplate example with expression *)
StringTemplate[ "here's a list <*Table[x,{x,1,5}]*>"][]
(* here's a list {1, 2, 3, 4, 5} *)

Formatting String, and Convert to Binary, Hexadecimal

Wolfram. String