LISP - Escape Sequences
Lisp - Characters and Strings
Section titled “Lisp - Characters and Strings”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.
Primary Escape Sequences in Strings
Section titled “Primary Escape Sequences in Strings”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\\...".
How to Handle Newlines and Tabs
Section titled “How to Handle Newlines and Tabs”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.
~%informat: The~%directive in aformatcontrol string inserts a newline.~tinformat: The~tdirective handles tabulation.- Literal Newlines: You can simply press Enter within a string literal in your editor. The resulting string will contain the newline character.
Code Examples
Section titled “Code Examples”Let’s see these concepts in action. Save the following code as main.lisp and run it.
main.lisp
Section titled “main.lisp”(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)Expected Output
Section titled “Expected Output”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 itemPro-Tip: Characters vs. Strings
Section titled “Pro-Tip: Characters vs. Strings”It’s important to distinguish between a string and a character in Lisp:
- A character literal is written with a
#\prefix. For example,#\Ais the character ‘A’, and#\Spaceis 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)