开发者

Clojure sprintf?

There is printf. It prints direc开发者_StackOverflow中文版tly to stdout.

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


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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜