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?
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)
In Clojure it's called format and resides in clojure.core
: printf
is equivalent to (comp print format)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With