I understand that this is trivial with an if, but is there an option, like %S
or %s
that interpolates nil as no string at all?
Example:
(format "%?.el" nil) ; ".el"
(format "%?.el" "beginner") ; "beginner.el"
Depending on your application, concat
might be of use:
(concat "live long " nil "and prosper")
;; => "live long and prosper"
This works because concat acts on sequences, and nil is an empty list.
The special form or
is useful here. This macro returns the value of the first argument, unless it's nil in which case it returns the second. So, assuming the variable you want to check is foo
, the following will do what you want:
(format "%s.el" (or foo ""))
In some ways it's better than a magic tag since it makes it clear what value should be returned if the argument is nil.
interpolation
tag.format
indicator for this (useM-x report-emacs-bug
for that). The rest of us have gotten used to usingconcat
for this, sometimes in combination withformat
(for other conversions). Or else passing an arg toformat
such as(if something "foobar" "")
, corresponding toformat
indicator"%s"
.rx
macro in such a scenario. At minimum make sure you areregexp-quote
ing as appropriate), but that aside if you have a large number of maybe-strings in LIST you could always do something like(apply 'format "%s%s%s%s" (mapcar (lambda (x) (or x "")) LIST))
. Of course if your format string is literally like"%s%s%s"
, thenconcat
does indeed make more sense.