chapter eighteen
format, printf and cl-format are functions dedicated to string formatting. format is a wrapper around Java’s String::format method, which is inspired by the venerable printf function from the C language. In Clojure printf is a small function wrapping println with format.
cl-format is instead a port of Common Lisp’s format function, formerly an external package called XP [244].
We’ve seen both format and cl-format in action many times throughout the book. Here’s a few examples for review:
- In memoize, we used
formatto print the cache hit (or miss) information.
- In rand we used
formatto print a text-based progress indicator.
- In vec we used
formatto render a simple JSON snippet.
- In Chapter 1, when describing how to improve printing of decimal values, we used
cl-formatin the XML example.
format has a rich set of formatting directives. The reader is invited to check the java.util.Formatter API reference for the full details [245], but here’s a group of useful examples:
(format "%3d" 1) ;; " 1" ; #1 (format "%03d" 1) ;; "001" ; #2 (format "%.2f" 10.3456) ;; "10.35" ; #3 (format "%10s", "Clojure") ;; " Clojure" ; #4 (format "%-10s", "Clojure") ;; "Clojure " ; #5 (format "%-11.11s" "truncatefixedsize") ;; "truncatefix" ; #6 (format "%tT" (java.util.Calendar/getInstance)) ;; "22:15:11" ; #7