18 Formatting and Printing

 

This chapter covers:

18.1  format, printf and cl-format

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. [229].

We’ve seen both format and cl-format in action in the book. Here’s a few pointers to interesting examples for review:

  • In memoize we used format to print the cache hit or miss information.
  • In rand we used format to print a text-based progress handler.
  • In vec we used format to render a simple JSON snippet.
  • We used cl-format in Chapter 1 when describing how to improve printing of decimal values in the XML example.

format has a rich set of formatting directives. The reader is invited to check the java.util.Formatter Java documentation for the full details, 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

18.2  pr, prn, pr-str, prn-str, print, println, print-str, println-str

18.3  pprint, pp, write and print-table

18.4  print-method, print-dup and print-ctor

18.5  slurp and spit

sitemap