Elisp: Format String

By Xah Lee. Date: .

How a lisp object is converted to string for printing is done by the format function. It takes a input string, and several other arguments of lisp objects, and output a string. Alt+x describe-function to lookup its doc string. Here's a excerpt:

(format STRING &rest OBJECTS)

Format a string out of a format-string and arguments.
The first argument is a format control string.
The other arguments are substituted into it to make the result, a string.

The format control string may contain %-sequences meaning to substitute
the next available argument:

%s means print a string argument.  Actually, prints any object, with `princ'.
%d means print as number in decimal (%o octal, %x hex).
%X is like %x, but uses upper case.
%e means print a number in exponential notation.
%f means print a number in decimal-point notation.
%g means print a number in exponential notation
  or decimal-point notation, whichever uses fewer characters.
%c means print a number as a single character.
%S means print any object as an s-expression (using `prin1').


For example, if you want to print a date format in yyyy-mm-dd, padding with leading “0”, you can do:

;; format yyyy-mm-dd, ISO 8601 format
(print (format "%04d-%02d-%02d" 2012 4 10))

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode



Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc