TransWikia.com

How to programmatically surround a string with escaped double-quote

Emacs Asked by lawlist on September 2, 2021

It seems that my question should be common knowledge, and I thought I knew it (at some point in the distant past), but the answer escapes me tonight. I’d like to take a string like "foo" and programmatically convert it to ""foo"". Is there a built-in function for that?

I realize I can (concat """ "foo" """), but I thought there is probably an existing function that does this.

One Answer

You might be thinking of prin1-to-string:

(prin1-to-string "foo")
=> ""foo""

You probably need some protection though (ensure it's a string, strip text properties, etc.), because you'll get more than you bargained for if you try it with a propertized string:

(prin1-to-string (propertize "foo" 'bar "baz"))
=> "#("foo" 0 3 (bar "baz"))"

In that case you'll also need to ensure the properties have been removed. For example:

(let* ((str (propertize "foo "bar"" 'bar "baz")))
  (set-text-properties 0 (length str) nil str)
  (prin1-to-string str))
=> ""foo \"bar\"""

Correct answer by ebpa on September 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP