Is there a sprintf() command (some command that takes a printf-style format string and a list of values to insert into the string) or something very much like it (preferably with a similar style of format specifiers)? Or, alternately, how would I implement sprintf() in Mathematica?

5 Answers
5

I've had a need for such a function several times, and I found this implementation of C-style *printf functions, by Vlad Seghete. To use it, all you need to do is extract the files to $UserBaseDirectory/MathPrintF/ and you're all set.

Limited Functionality

While we tried to mimic the C-standard as much as possible, only certain
features are implemented. These are mainly dictated by what we needed at
the time. In particular %d, %f, %e, %E and %s with most of their options
are implemented.

This is a floating point: 5.6e9
This is a integer in blocks : 1,000,000,000
This is a number with funny padding : ____6.888 This isjust a string : FOO
"This is a floating point: 5.6e9\nThis is a integer in blocks : 1,000,000,000\nThis is a number with funny padding : ____6.888 This is just a string : FOO "

Mathematica does not have a built-in equivalent to sprintf. The closest thing is StringForm which allows placeholders within a string to be replaced, but does not perform any formatting of the replacement values:

Yes, the formatting has to be done on the control string and parameter strings themselves. E.g., StringForm["`1` is in InputForm, while `2` is in TraditionalForm, you see!", InputForm[Exp[x]], TraditionalForm[Exp[x]]].
–
Guess who it is.♦Jan 30 '12 at 1:50

@J.M. exactly. (You need a longer name to allow all of us to enter very short responses to your nuggets of wisdom. And, why yes, I'm intentionally leaving an extra long comment just because.)
–
rcollyerJan 30 '12 at 2:19

I thought an example would be in order, please review my edit.
–
SzabolcsJan 30 '12 at 9:46

Mathematica is a registered trademark of Wolfram Research, Inc. While the mark is used herein with the limited permission of Wolfram Research, Stack Exchange and this site disclaim all affiliation therewith.