common-lisp Basic Usage and Simple Directives


The first two arguments to format are an output stream and a control string. Basic use does not require additional arguments. Passing t as the stream writes to *standard-output*.

> (format t "Basic Message")
Basic Message

That expression will write Basic Message to standard output, and return nil.

Passing nil as the stream creates a new string, and returns it.

> (format nil "Basic Message")
"Basic Message"

Most control string directives require additional arguments. The ~a directive ("aesthetic") will print any argument as though by the princ procedure. This prints the form without any escape characters (keywords are printed without the leading colon, strings without their surrounding quotes and so forth).

> (format nil "A Test: ~a" 42)
"A Test: 42"
> (format nil "Multiples: ~a ~a ~a ~a" 1 (list 2 3) "four five" :six)
"Multiples: 1 (2 3) four five SIX"
> (format nil "A Test: ~a" :test)
"A Test: TEST"
> (format nil "A Test: ~a" "Example")
"A Test: Example"

~a optionally right or left-pads input based on additional inputs.

> (format nil "A Test: ~10a" "Example")
"A Test: Example   "
> (format nil "A Test: ~10@a" "Example")
"A Test:    Example"

The ~s directive is like ~a, but it prints escape characters.

> (format nil "A Test: ~s" 42)
"A Test: 42"
> (format nil "Multiples: ~s ~s ~s ~s" 1 (list 2 3) "four five" :six)
"Multiples: 1 (2 3) \"four five\" :SIX"
> (format nil "A Test: ~s" :test)
"A Test: :TEST"
> (format nil "A Test: ~s" "Example")
"A Test: \"Example\""