String Formatting

One of the things we programmers do all the time is to build strings of the sort

In a survey of 342 programmers, 312 preferred Emacs.

where the two numbers and the string “Emacs” are variables. If, like me, you have multiple decades of C experience, the first thing you think of is printf. In C, you would render the above string as

(printf "In a survery of %d programmers, %d preferred %s",
 survey_total, editor_total, editor_type);

This idiom is so well established that you seldom see it done any other way.

Emacs Lisp has a direct analogue called format. Those of us permanently imprinted with the printf pattern seldom think of doing it any other way but Elisp offers several other methods of producing such strings.

John Kitchin has just posted a very nice video that considers several ways of formatting strings. He admits that he usually reaches first for format but some of the other methods he considers make the code more readable.

He looks at six ways of formatting strings:

  1. format
  2. format-spec
  3. f-string
  4. s-string
  5. mustache
  6. templatel

The first two are built in and the others are contributed functions. My years of C have permanently warped my brain so I stick to format almost all the time. If you like to make your code a little less opaque, you might want to give the others a try. The video is a good demonstration of their use.

The video is just over 22 and a half minutes so you’ll need to schedule some time. As usual with Kitchin’s videos, you learn things you probably didn’t know so it’s definitely worthwhile spending a few minutes with it.

This entry was posted in General and tagged , . Bookmark the permalink.