我一直在努力让它正确几个小时,但我仍然无法弄清楚。该死。格式功能太混乱了。
基本上我需要的是将列表转换为字符串。该列表可以包含字符串,结果字符串中的那些字符串应该是双转义的。这就是我的意思:
如果我有((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))\""
Run Code Online (Sandbox Code Playgroud)
prin1-to-string
等价于write-to-string
with: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))\""
Run Code Online (Sandbox Code Playgroud)
正如@RainerJoswig 指出的那样,您还可以使用format
with ~s
which 打印转义字符,就像使用prin1一样:
CL-USER> (format nil "~s" (format nil "~s" '((one "foo") (two 42))))
"\"((ONE \\\"foo\\\") (TWO 42))\""
Run Code Online (Sandbox Code Playgroud)