对格式功能很困惑
Very confused with format function
几个小时以来,我一直在努力把它弄好,但我还是想不通。
该死。格式函数太混乱了。
基本上我需要的是将列表转换成字符串。该列表可以包含字符串,结果字符串中的那些字符串应该双重转义。这就是我的意思:
如果我有 ((one "foo") (two 42))
,结果字符串应该如下:
"\"((one \\"foo\\") (two 42)\""
- 请注意整个字符串都在双引号中,这就是 "foo" 必须被包裹两次的原因。
而且我无法破解这个。有人请帮助。
您可以使用prin1-to-string
,两次:
CL-USER> (prin1-to-string (prin1-to-string '((one "foo") (two 42))))
"\"((ONE \\"foo\\") (TWO 42))\""
prin1-to-string
等价于 write-to-string
和 :escape t
以便写入转义字符;但是使用 prin1-to-string
比笨拙的更好:
CL-USER> (write-to-string
(write-to-string '((one "foo") (two 42)) :escape t)
:escape t)
"\"((ONE \\"foo\\") (TWO 42))\""
您还可以将 format
与 ~s
which prints escape characters as if by prin1, as 一起使用:
CL-USER> (format nil "~s" (format nil "~s" '((one "foo") (two 42))))
"\"((ONE \\"foo\\") (TWO 42))\""
几个小时以来,我一直在努力把它弄好,但我还是想不通。 该死。格式函数太混乱了。
基本上我需要的是将列表转换成字符串。该列表可以包含字符串,结果字符串中的那些字符串应该双重转义。这就是我的意思:
如果我有 ((one "foo") (two 42))
,结果字符串应该如下:
"\"((one \\"foo\\") (two 42)\""
- 请注意整个字符串都在双引号中,这就是 "foo" 必须被包裹两次的原因。
而且我无法破解这个。有人请帮助。
您可以使用prin1-to-string
,两次:
CL-USER> (prin1-to-string (prin1-to-string '((one "foo") (two 42))))
"\"((ONE \\"foo\\") (TWO 42))\""
prin1-to-string
等价于 write-to-string
和 :escape t
以便写入转义字符;但是使用 prin1-to-string
比笨拙的更好:
CL-USER> (write-to-string
(write-to-string '((one "foo") (two 42)) :escape t)
:escape t)
"\"((ONE \\"foo\\") (TWO 42))\""
您还可以将 format
与 ~s
which prints escape characters as if by prin1, as
CL-USER> (format nil "~s" (format nil "~s" '((one "foo") (two 42))))
"\"((ONE \\"foo\\") (TWO 42))\""