Common Lisp相当于格式函数里面的\ r \n?

40 format newline common-lisp

基本上,我想做以下事情,只使用Common Lisp而不是Python:

print("Hello world.\r\n")
Run Code Online (Sandbox Code Playgroud)

我可以这样做,但它只输出#\newline字符并跳过#\return:

(format t "Hello world.~%")
Run Code Online (Sandbox Code Playgroud)

我相信我可以使用外部参数完成此操作,如下所示:

(format t "Hello world.~C~%" #\return)
Run Code Online (Sandbox Code Playgroud)

但对我来说似乎很尴尬.当然,我可以以某种方式嵌入#\return到格式字符串中,就像我可以一样#\newline

Rai*_*wig 58

返回和换行的字符

\r#\returnCommon Lisp中的角色.

\n#\linefeedCommon Lisp中的角色.

以下结束"Hello world."带有return和换行的字符串.

(format t "Hello world.~C~C" #\return #\linefeed)
Run Code Online (Sandbox Code Playgroud)

#\newline是平台用作线路划分的任何东西.在Unix机器上,这通常是相同的#\linefeed.在其他平台上(Windows,Lisp Machines,...),这可能会有所不同.

格式控制

FORMAT控制~%打印换行符(!).

所以

(format t "Hello world.~%")
Run Code Online (Sandbox Code Playgroud)

将打印操作系统使用的换行符.CR或CRLF或LF.根据平台,这将是一个或两个字符.

所以,在Windows机器上你的

(format t "Hello world.~C~%" #\return)
Run Code Online (Sandbox Code Playgroud)

可能实际打印:#\return #\return #\linefeed.这是三个字,而不是两个.Windows将CRLF用于换行.Unix使用LF.旧Mac OS(Mac OS X之前)和Lisp Machines将CR用于换行.

写CRLF

如果您真的想要打印CRLF,则必须明确地执行此操作.例如:

(defun crlf (&optional (stream *standard-output*))
  (write-char #\return stream)
  (write-char #\linefeed stream)
  (values))
Run Code Online (Sandbox Code Playgroud)

FORMAT 没有用于输出换行符或回车符的特殊语法.

FORMAT控件中的换行符

Common Lisp允许多行字符串.因此我们可以将它们用作格式控件:

在这里你可以看到控制字符串中的换行符也在输出中:

CL-USER 77 > (format t "~%first line
second line~%~%")

first line
second line

NIL
Run Code Online (Sandbox Code Playgroud)

下面是一个示例,其中~@FORMAT控件保留换行符,但删除下一行的空格:

CL-USER 78 > (format t "~%first line~@
                          second line~%~%")

first line
second line

NIL
Run Code Online (Sandbox Code Playgroud)

  • 1、1 和 1 为长度。with (with-open-file (s #p"c:\\foo.txt" :direction :output :if-exists :supersede) (write-string (format nil "~%") s)), SBCL 和 CCL吐出一个包含 \#Newline 的 1 字节文件。Clip 吐出一个 1 字节的文件,其中包含一个 #\Return! (3认同)
  • 在 Windows 上的 SBCL 1.0.22、CLISP 2.47 和 Clozure CL 1.3 中:(aref (format nil "~%") 0) 返回 #\Newline。 (2认同)

Ram*_*ren 5

首先,在Common Lisp中,大多数字符,包括return/newline,都可以直接插入到字符串中.唯一需要转义的字符是字符串分隔符.

还有一个库cl-interpol,它提供了一个读取宏来构造具有更复杂语法的字符串,包括特殊字符转义.