views:

130

answers:

3
+5  Q: 

Clojure sprintf?

There is printf. It prints directly to stdout.

How about sprintf, which formats the same way as printf, but returns a string with no side-effects?

+7  A: 

In Clojure it's called format and resides in clojure.core: printf is equivalent to (comp print format).

Michał Marczyk
+4  A: 

You should check out cl-format, in the clojure.pprint lib. It's a port of Common Lisp's FORMAT function. It can do things that Java's printf can't do, like conditionals, iterating over seqs, etc.

To answer your question, with cl-format, a first argument of nil will return a string; a first argument of true will print to STDOUT.

user> (cl-format nil "~{~R~^, ~}" [1 2 3 4])
"one, two, three, four"

Note that if format didn't already exist in Clojure, you could also capture the output from Clojure's printf like this:

user> (with-out-str (printf "%s" :foo))
":foo"

with-out-str is helpful when a library only provides a function that prints to STDOUT and you want to capture the output instead. I've run across Java libraries that do this.

Brian Carper
+2  A: 

Consider using the with-out-str macro:

(with-out-str
    (print x))

Or just call java.lang.String's format method:

(String/format "%d" 3)
bendin