Skip to content

LISP - Escape Sequences

In Common Lisp, strings are sequences of characters. Unlike languages like C or Python, Lisp strings have very few escape sequences. Special characters are typically handled by functions or format control sequences rather than being embedded directly in the string literal.

Within a string literal (delimited by double quotes "), there are only two characters that require escaping with a backslash (\):

  • \" - Includes a literal double quote character inside the string. Example: "He said, \"Greetings!\"".
  • \\ - Includes a literal backslash character inside the string. Example: "This is a file path: C:\\Users\\...".

While some Lisp implementations might support \n or \t, the portable and idiomatic way to handle control characters is through the format function or by writing literal newlines in your source code.

  • ~% in format: The ~% directive in a format control string inserts a newline.
  • ~t in format: The ~t directive handles tabulation.
  • Literal Newlines: You can simply press Enter within a string literal in your editor. The resulting string will contain the newline character.

Let’s see these concepts in action. Save the following code as main.lisp and run it.

(defun demonstrate-strings ()
;; Example 1: Escaping a double quote
(let ((quote-string "She exclaimed, \"Lisp is powerful!\""))
(format t "Example 1: ~a~%" quote-string))
(terpri) ; Print a blank line for separation
;; Example 2: Escaping a backslash
(let ((path-string "A windows-style path: C:\\Temp\\File"))
(format t "Example 2: ~a~%" path-string))
(terpri)
;; Example 3: Using FORMAT for newlines and tabs
(format t "Example 3:~%")
(format t "\t- First item~%\t- Second item~%"))
;; Run the demonstration
(demonstrate-strings)

Executing this code will produce the following result:

Example 1: She exclaimed, "Lisp is powerful!"
Example 2: A windows-style path: C:\Temp\File
Example 3:
- First item
- Second item

It’s important to distinguish between a string and a character in Lisp:

  • A character literal is written with a #\ prefix. For example, #\A is the character ‘A’, and #\Space is the space character.
  • A string is a sequence of characters, written inside double quotes, like "Hello".
  • This distinction is important for functions that operate specifically on characters, such as char= for comparison.
(characterp #\a) ; => T
(stringp "a") ; => T
(string= "a" (string #\a)) ; => T (they can be compared if converted)