Apparently, Mathematica has no real sprintf-equivalent (unlike any other high-level language known to man). This has been asked before, but I'm wondering if the new StringTemplate
function in Mathematica 10 can be extended to include such formatting capabilities.
What I have in mind is a function that takes a TemplateObject
, and looks for "formatting specification strings" immediately after TemplateSlot
's and TemplateExpression
's and replaces them with TemplateExpression
's containing appropriate formatting code. So, for example, you could write:
st = applyFormat@StringTemplate["Number: `1`%.2 some other text"]
and you would get something equivalent to:
TemplateObject[{"Number: ",
TemplateExpression[ToString[NumberForm[TemplateSlot[1], {\[Infinity], 2}]]],
" some other text"}, InsertionFunction -> TextString,
CombinerFunction -> StringJoin]
I'm not particularly picky about the syntax (it doesn't have to mimic sprintf), as long as:
- it's easy to write and easy to read
- it supports Mathematica's number formatting functions (
AccountingForm
,ScientificForm
...) - it's extensible (e.g by delegating the formatting to a pattern that can be overwritten/extended)
- it's compatible with existing
StringTemplate
templates
I've started a function that does this, but I'm curious if you have better ideas (both implementation- and syntax-wise), so I'm posting it as an answer, not as part of the question.
Comments
Post a Comment