Lisp - Escape Sequences in Strings



In Lisp, we can use escape sequence using backslash (\) before them. A escape sequence is a special character combination which have special meanings. Following are some of the important escape sequence in Lisp −

  • \"− Includes a double quote character within a string already delimited by double quotes. For example: "She said, \"Hi!\"".

  • \\− Includes a backslash character in a string. For example: "This is a backslash symbol: \\".

  • \n− Inserts a newline character. A newline character inserts a new line. For example: "First Line.\nSecond Line.\nThird Line.".

  • \r− Carriage Return character moves cursor to the beginning of the current line.

  • \t− Tab character, representing few spaces.

  • \a− Alarm bell, a system-dependent audible alert.

  • \b− Backspace character moves the cursor one position to the left.

  • \f− Form feed character to advance the printer to the next page (system dependent behavior).

  • \v− Vertical character, to move the cursor to the next tab position.

  • \x− Hexadecimal character code, to represent a character by its hexadecimal code. For example, \x41 represents the character 'A' (ASCII code 65).

Example - Using Double Quote Character

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; define a string with a double quote
(defparameter greeting "She said, \"Hi!\"")

; print the string
(format t "~a" greeting)

Output

When you execute the code, it returns the following result −

She said, "Hi!"

Example - Using Backslash Character

Update file named main.lisp and type the following code in it.

main.lisp

; define a string with a backslash
(defparameter message "Title:, \\A Special Package\\")

; print the string
(format t "~a" message)

Output

When you execute the code, it returns the following result −

Title:, \A Special Package\
Advertisements